javascript - AngularJS: Why does $element.find('option') return an empty array when using ng-options? -
in angular 1.4, using ngoptions directive populate <select> tag <option> tags based on object looks this:
{black: '#000000', red: '#ff0000', ...} that works fine using ng-options="value key (key, value) in vm.colors", want add class each option tag matches key (e.g. '.black', '.red'). thought find option elements , use addclass(), i'm having trouble getting elements. (note: i'm not using jquery , avoid adding this.)
i expect able bind results of $element.find('option') view model , watch using $scope.$watch('vm.options', function() {...}), when log vm.options console seeing empty array.
am using $scope.$watch incorrectly here? issue $element? elements within scope of ngoptions unreachable controller? or making stupid mistake?
any appreciated...thanks in advance!
the docs pretty clear dom manipulation should done in directive. use rule of thumb: if find myself wanting or needing use angular.element, need directive.
in case, can use built in ngstyle directive:
(function() { 'use strict'; var hexcolors = { black : '#000000', red : '#ff0000', green : '#00ff00', blue : '#0000ff' }; angular.module('sandbox', []) .constant('hexcolors', hexcolors) .controller('sandboxcontroller', sandboxcontroller) ; function sandboxcontroller($element, $scope) { var vm = this; vm.colors = hexcolors; vm.selected = '#000000'; } })(); <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script> <div ng-app="sandbox" ng-controller="sandboxcontroller vm"> <select ng-model="vm.selected" ng-options="value key (key, value) in vm.colors"></select> <p ng-style="{'background-color': vm.selected, color: 'white'}">hex: {{ vm.selected }}</p> </div>
Comments
Post a Comment