首页 > $http取得的数据在指令中没有正常显示

$http取得的数据在指令中没有正常显示

<html ng-app="app">
  <body ng-controller="appCtrl">
    <div ng-controller="myCtrl">
      <div class="my-select">
        <select ng-model="selected" ng-options="member.name for member in members">
          <option value="">Please select ...</option>
        </select>
        <div>options: {{options}}</div>
        <div>
          length of options: <span class="num"></span>
        </div>
        <div>selected: {{selected.name}}</div>
      </div>
    </div>
  </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('<div class="members"></div>');
        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 请戳这里

【热门文章】
【热门文章】