2016-04-21 65 views
0

我看過這個video,我有一個問題,我找不到答案。有一個plunker http://plnkr.co/edit/L8OMoB?p=previewAngularJS指令鏈接功能執行順序與要求

HTML

<div ng-app="app"> 
      <div ng-controller="MyCtrl"> 
       <my-select-view on="color"> 
        <my-view label="Red" value="red"><span class="red-text">Red Content</span></my-view> 
        <my-view label="Blue" value="blue"><span class="blue-text">Blue Content</span></my-view> 
        <my-view label="Green" value="green"><span class="green-text">Green Content</span></my-view> 
        <my-view label="Something" value="something"><span class="something-text">Something Content</span></my-view> 
       </my-select-view> 
      </div> 
     </div> 

JS

angular.module('app', ['ngSanitize']) 
     .directive("mySelectView", function($compile) { 

      return { 
       restrict: "E", 
       scope: { item : "=on"}, 
       controller: function($scope, $element) { 
        $scope.views = []; 

        this.addView = function(label, value, content) { 
         $scope.views.push({ label: label, value: value, content: content }); 
        } 

       }, 
       link: function(scope, element, attrs, ctrl) { 
        var selectTpl = "<select ng-model='item'" + 
            "  ng-options='view.value as view.label for view in views'" + 
            "  ng-change='changeView()'></select>"; 

        ... 

       } 
      } 
     }) 
     .directive("myView", function() { 
      return { 
       restrict: "E", 
       require: "^mySelectView", 
       link: function(scope, element, attrs, ctrl) { 
        ctrl.addView(attrs.label, attrs.value, element.html()); 
       } 
      }; 
     }) 
     .controller("MyCtrl", function($scope) { 
      $scope.color = "something"; 
     }); 

我想知道的一件事。我們得到了指令「mySelectView」,其中包含「鏈接」功能。這個「鏈接」功能依賴於要被定義的「視圖」變量幷包含某些內容。

它獲得它的唯一方法是通過調用其他指令「myView」上的「鏈接」函數。該指令對先前的指令有一個require參數。

所以我的問題是:指令「myView」的「鏈接」功能後,如何執行指令「mySelectView」的「鏈接」功能。我假設這是因爲需要$ scope.views的「ng-option」屬性才能正確顯示內容。這意味着「myView」的鏈接功能可以執行並添加視圖。

但是如何?誰決定這個命令?爲什麼第一個指令的「鏈接」功能只是因爲未定義的$ scope.views而不快樂地失敗?

任何幫助,將不勝感激!

回答

1

$scope.views不是不確定的。相反,已初始化爲空數組$scope.views = [];

我希望這link會回答你的鏈接功能

+0

感謝鏈接的執行順序上的問題 - 我會讓我的研究 –