javascript - How can I access the options of an Angular select element? -
i'm trying write attribute directive used enhance select element. need access option children of select element part of enhancement (so i'd able access them in link function).
for example, here basic template:
<div ng-app="test" ng-controller="testctrl"> <select ng-model="selected" ng-options="i in data" enhanced></select> </div> a basic controller:
var t = angular.module("test", []); t.controller("testctrl", function ($scope) { $scope.data = [ "one", "two", "three" ]; $scope.selected = $scope.data[0]; }); and basic directive:
t.directive("enhanced", function () { return function ($scope, $element) { console.log($element.find("option").length); // 0 }; }); here's fiddle containing complete example.
the problem inside link function, ng-options directive has not yet executed , select element still empty. there way can defer execution of directive until ng-options directive complete? or there better way achieve this?
you use $timeout inside directive.
t.directive("enhanced", function ($timeout) { return function ($scope, $element) { $timeout(function(){ console.log($element.find("option").length); // 3 }) }; }); here fiddle
another option using watcher:
t.directive("enhanced", function () { return function ($scope, $element) { $scope.$watch('selected', function () { console.log($element.find("option").length); // 3 }); }; }); the problem approach run anytime expression changes have unwatch after first time.
here fiddle
Comments
Post a Comment