2015-08-19 29 views
0

我发指令的集合,但是当我更新父范围的收集,指令不更新集合:如何更新发送给它的收集时更新的指令更新?

http://jsfiddle.net/edwardtanguay/kj4oj1aa/9/

<div ng-controller="mainController"> 
    <div item-menu datasource="customers" add="addCustomer()"></div> 
    <button ng-click="addCustomer()">add customer</button> Number added: {{numberAdded}} 
    <ul> 
     <li ng-repeat="customer in customers">{{customer.lastName}}</li> 
    </ul> 
</div> 

我认为我需要一个$腕表在我的指令中的某处,但是在哪里以及如何实施?

指令:

.directive('itemMenu',function() { 

    var controller = function($scope) { 
     var vm = this; 
     function init() { 
      vm.items = angular.copy($scope.datasource); 
     } 
     init(); 
    }; 

    return { 
     restrict: 'A', 
     scope: { 
      datasource: '=', 
      add: '&' 
     }, 
     controller: controller, 
     controllerAs: 'vm', 
     bindToController: true, 
     templateUrl: 'itemMenuTemplate', 
     link: function(scope, element, attrs) { 
     scope.getTemplateUrl = function(item) { 
      switch(item.kind) { 
       case 'external': 
        return 'itemMenuTemplateExternal'; 
       case 'internal': 
        return 'itemMenuTemplateInternal'; 
       default: 
        return 'itemMenuTemplateUndefined'; 
      } 
     }; 
    }, 
    }; 

回答

1

由于您使用angular.copy,当$scope.datasource正在更新将不会更新。

为了深入观察,您需要在参数true上加上$ watch。我认为这是你的场景(这在性能方面被认为是相当昂贵的,所以请阅读$watch以查看是否应该使用其他方法,如$ watchCollection)。

var controller = function($scope) { 
    var vm = this; 

    $scope.$watch('datasource', function(newVal) { 
     copy(newVal); 
    }, true); 

    function copy(object) { 
     vm.items = angular.copy(object); 
    } 

    function init() { 
     //add other init code here 
     copy(vm.datasource); 
    } 

    init(); 
}; 
+0

嗯,好吧,我已经从示例代码得到了这一点,并认为angular.copy()是必要的某些原因,我根本就没有现在复制它('vm.items = $ scope.datasource;' ),它的工作现在指示更新罚款:http://jsfiddle.net/edwardtanguay/kj4oj1aa/11/ –