您的指令需要知道它正在监视哪个数组。您可以将它传递给指令,并让指令监视此数组。
我创建了一个小提琴,展示了这一点:http: //jsfiddle.net/TMVFN/1/
HTML:
</select>
<select ng-model="selectedA" ng-options="optA for optA in optionsA" ajax-charged="optionsA">
</select>
{{selectedA}}, {{selectedB}}
</div>
JS:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope, $timeout) {
$timeout(function(){
$scope.optionsA = ['opt1', 'opt2', 'etc'];
$scope.optionsB = ['opt4', 'opt5'];
}, 3000);
$scope.optionsB = ['opt3'];
$scope.selectedB = 'opt3';
};
myApp.directive('ajaxCharged', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, elm, attrs, ngModel) {
$scope.$watch(attrs.ajaxCharged, function(newVal, oldVal) {
console.log(newVal);
if (typeof(newVal) === 'undefined' ||
typeof(newVal.length) === 'undefined' ||
newVal.length === 0) {
$scope[attrs.ajaxCharged] = ['Charging...'];
} else if (newVal !== oldVal && newVal.length > 0) {
ngModel.$setViewValue(newVal[0]);
}
}, true);
}
};
});