<html ng-app="app">
<body ng-controller="appCtrl">
<p ng-controller="myCtrl">
<p class="my-select">
<select ng-model="selected" ng-options="member.name for member in members">
<option value="">Please select ...</option>
</select>
<p>options: {{options}}</p>
<p>
length of options: <span class="num"></span>
</p>
<p>selected: {{selected.name}}</p>
</p>
</p>
</body>
</html>
var app = angular.module('app', ['ui.bootstrap']);
app.controller('appCtrl', function($scope, $timeout) {
});
app.controller('myCtrl', function($scope, $http, $timeout) {
$http.get('data.json').success(function(data) {
$scope.members = data.members;
});
});
app.directive('mySelect', function($timeout) {
return {
restrict: 'AC',
link: function(scope, element, attrs) {
$timeout(function() {
scope.options = element.find('option');
options = element.find('option');
element.append('<p class="members"></p>');
var members = angular.element(document.querySelector('.members'));
for(var i=1;i<options.length;i++) {
members.append('<li>' + options.eq(i).attr('label')+'</li>');
}
},100);
$timeout(function() {
angular.element(document.querySelector('.num')).text(options.length);
},100);
}
}
});
上述代码中,select中的确是取到了$scope.members中的数据,但是在指令中 for(var i=1;i<options.length;i++) {...} 该for循环却没有得到执行,因为 options.length 一直为1。
在指令中已经使用了$timeout了,但是还是没有正常取到options。
plunker 请戳这里
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
走同样的路,发现不同的人生