Saturday 15 March 2014

angularjs - Angular.js - adding a class to an option with ng-options -



angularjs - Angular.js - adding a class to an option with ng-options -

someone asked similar question (how utilize ng-class in select ng-options), i'm adding mine too, because it's related reply of other guy's question.

the solution awesome, don't quite understand it.

the reply creating directive - http://plnkr.co/edit/rbc4gwbffi4efyhbvs6u?p=preview.

i same, class added should same items.name. how do that?

class="snippet-code-js lang-js prettyprint-override">console.clear(); var app = angular.module('angularjs-starter', []); app.controller('mainctrl', function($scope) { $scope.items = [ { name: 'foo', id: 1, eligible: true }, { name: 'bar', id: 2, eligible: false }, { name: 'test', id: 3, eligible: true } ]; }); app.directive('optionsclass', function ($parse) { homecoming { require: 'select', link: function(scope, elem, attrs, ngselect) { // source items array populates select. var optionssourcestr = attrs.ngoptions.split(' ').pop(), // utilize $parse function options-class attribute // can utilize evaluate later. getoptionsclass = $parse(attrs.optionsclass); scope.$watch(optionssourcestr, function(items) { // when options source changes loop through items. angular.foreach(items, function(item, index) { // evaluate against item mapping object // classes. var classes = getoptionsclass(item), // alternative you're going need. can found // looking alternative appropriate index in // value attribute. alternative = elem.find('option[value=' + index + ']'); // loop through key/value pairs in mapping object // , apply classes evaluated truthy. angular.foreach(classes, function(add, classname) { if(add) { angular.element(option).addclass(classname); } }); }); }); } }; }); class="snippet-code-css lang-css prettyprint-override">/* css goes here */ .is-eligible { color: green; } .not-eligible { color: red; } class="snippet-code-html lang-html prettyprint-override"><!doctype html> <html ng-app="angularjs-starter"> <head lang="en"> <meta charset="utf-8"> <title>custom plunker</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script> <link rel="stylesheet" href="style.css"> <script> document.write('<base href="' + document.location + '" />'); </script> <script src="app.js"></script> </head> <body ng-controller="mainctrl"> <select ng-model="foo" ng-options="x.name x in items" options-class="{ 'is-eligible' : eligible, 'not-eligible': !eligible }"></select> </body> </html>

thanks in advance

one way hard-coding logic directive using option.text():

angular.element(option).addclass(option.text()); //

however, ignore expression. http://plnkr.co/edit/46hndjytg6hubblncenr?p=preview

angularjs angularjs-directive ng-options

No comments:

Post a Comment