2015-02-09 50 views
2

我正在使用帶有controllerAs語法的指令。我想使用該指令的兩個實例,它們都需要非共享數據。我的問題,似乎只有控制器實例。多個帶控制器的angularjs指令實例作爲語法

似乎可以選擇在指令聲明中添加範圍:{}。但是,那麼我將被迫使用基於範圍的訪問?

還是有其他方式仍然使用controllerAs /這個語法,並強制角度創建2個不同的控制器對象嗎?

app.directive('createA', function() { 
    return { 
     restrict : 'E', 
     templateUrl : '/template/createActivity', 

     // using this to create 2 distinct scopes 
     // but then I can't use the this/caCtrl.data syntax? 
     scope  : {}, 

     controller : function($scope, $rootScope) { 

      // using this syntax to access data 
      // in tempate like {{ caCtrl.data }} 
      this.data = '123'; 
     }, 
     controllerAs : 'caCtrl' 

    }; 
}); 

回答

2

我意識到這個問題已經很老了,但如果有人絆倒它,並需要一個不同的解決方案,第一個答案中提到的「bindToController」屬性沒有爲我做。

我有一個類似的場景,我需要使用controllerAs語法實例化多個指令,這是我如何解決它(應用於示例的指令)。它可能不太優雅,但它的工作原理。

app.directive('createA', function() { 
    return { 
     restrict : 'E', 
     templateUrl : '/template/createActivity', 

     // using this to create 2 distinct scopes 
     // but then I can't use the this/caCtrl.data syntax? 
     // scope  : {}, //do not use isolated scope 
     controller: function ($scope, $rootScope, $attrs) { 

      var controllerAsName = !!$attrs.ctrlName ? $attrs.ctrlName : 'caCtrl'; 

      var self = $scope[controllerAsName] = {}; 

      // using this syntax to access data 
      // in tempate like {{ caCtrl.data }} 
      self.data = '123'; 
     }, 
     // controllerAs : 'caCtrl' //do not specify controllerAs since you are "manually handling" it 
}); 

當在HTML中使用你的指令,你會使用這樣的:

<create-a ctrl-name="foo">foo.data</create-a> 
<create-a ctrl-name="bar">bar.data</create-a> 

我不知道該指令的模板標記是什麼,所以我的解決方案可能沒有什麼意義爲你,但你明白了。

+0

我覺得Angular讓控制器在指令實例之間共享令人驚訝。任何人都可以解釋爲什麼這將作爲默認行爲更令人滿意,而不是指令有自己的控制器和數據? – Pistos 2016-08-19 14:18:31

+0

如果您需要具有不同的實例數據,只需使用scope:{}並創建一個獨立的作用域,然後使用作用域對象來存儲數據。否則,請執行OP的操作,並傳入一個額外參數,並將其作爲映射存儲在控制器級別。 – Tigertron 2017-04-25 16:37:09