2015-07-19 39 views
0

我想這樣做: 我有一個Angular 裏面的對象數組,我想編寫一個指令,爲該數組的每個成員創建一個div元素HTML視圖,如果新項目來到數組,自動查看更新,並且如果刪除項目,HTML更新也是如此。我這樣做:在Angular指令裏面添加子視圖到HTML視圖

這是我的控制器:

app.controller("timelineCtrl", function ($scope) { 
    $scope.arr={}; 
     . 
     . 
     . 
} 

這是我的指令:

app.directive('helloWorld', function() { 
    return { 
     restrict: 'AE', 
     replace: true, 
     template: '<div> Hello {{arrayItem}} </div>', 

     link: function ($scope, element, attrs) { 
      //here i know that i have to write some code 
      // i have to watch any changes in array and compile it to HTML view 
     } 
    }; 
}); 

這是我的看法:

<div class="row" ng-controller="timelineCtrl"> 
    <hello-world></hello-world> 
</div 

我知道我必須寫link指令的屬性內的一些代碼,但我不能這樣做。我必須爲該數組創建一個循環並檢查值?

回答

0

角有ng-repeat指令來顯示項目形成陣列。 出於您的目的,您可以創建一個負責單項邏輯的指令,並使用ng-repeat來呈現這些項目。吳重會照顧有關添加或刪除項目從數組:

<div class="row" ng-controller="timelineCtrl"> 
    <hello-world ng-repeat="arrayItem in arr" array-item="arrayItem"></hello-world> 
</div 

項數據傳播到指令,你應該做這個配置

app.directive('helloWorld', function() { 
    return { 
    restrict: 'AE', 
    template: '<div> Hello {{arrayItem}} </div>', 
    scope: { 
     arrayItem: '=' // this means that scope value should be taken from attribute with corresponding name 
    }, 

    link: function ($scope, element, attrs) { 
     // your logic with single arrayItem 
     // item available as $scope.arrayItem 
    } 
    }; 
}); 

您可以更多地瞭解它是如何工作的角度docs,在that page看到「範圍」部分

+0

你能完成鏈接部分嗎?它不適用於我 – Fcoder

+0

你期望什麼?看[我的代碼](http://jsfiddle.net/27LpcosL/),列表中有三個項目 –

0

這樣的事情呢? 用ng-repeat處理數組將處理新的和已刪除的項目。 (您wdont需要在鏈接功能做任何事情)

app.directive('helloWorld', function() { 
     return { 
      restrict: 'AE', 
      replace: true, 
      scope:{ 
        arrayItem: '=ngModel' 
       }, 
     template: '<div> Hello {{arrayItem}} </div>', 

    }; 
}); 


<div class="row" ng-controller="timelineCtrl"> 
    <hello-world ng-repeat="arrayItem in arr" ng-model="arrayItem"></hello-world> 
</div>