2016-05-04 64 views
1

據我所知,在'Directive Definition Object'上使用控制器屬性時,每次給定指令被鏈接時都會創建該控制器的單獨實例?在控制器中使用指令As

現在正在使用controllerAs模式我可以看到,當每個指令正在編譯時,控制器工廠函數正在觸發給this.data.hello方法不同的結果。

但在我看來,我得到了該控制器的最後一個實例。這是爲什麼?我錯過了什麼?

JS

angular.module('app', []) 
    .controller('customCtrl', function() { 
     console.log('controller'); 

     this.data = { 
      hello: Math.floor(Math.random() * 200 + 1) 
     }; 
    }) 
    .directive('customDrv', function() { 
     var linkFn = function (scope, element, attrs, ctrl) { 
      console.log('link'); 
      console.log(ctrl.data.hello); 
     }; 

     return { 
      templateUrl: 'Home/CustomDrv', 
      restrict: 'E', 
      controller: 'customCtrl', 
      controllerAs: 'vm', 
      compile: function (element, attrs) { 
       console.log('compile'); 

       return linkFn 
      } 
     } 
    }) 

的Html

<custom-drv></custom-drv> 
<custom-drv></custom-drv> 
<custom-drv></custom-drv> 
<custom-drv></custom-drv> 

Plunker:https://plnkr.co/edit/HII9a7Ff6ryXuz6Fgzr6

回答

3

要獲得this.data.hello方法不同的結果創建隔離範圍爲 -

angular.module('app', []) 
    .controller('customCtrl', function() { 
     //console.log('controller'); 

     this.data = { 
      hello: Math.floor(Math.random() * 200 + 1) 
     }; 
    }) 
    .directive('customDrv', function() { 
     var linkFn = function (scope, element, attrs, ctrl) { 
      //console.log('link'); 
      console.log(ctrl.data.hello); 
     }; 

     return { 
      template: '<h1>{{vm.data.hello}}</h1>', 
      restrict: 'E', 
      scope: {}, 
      controller: 'customCtrl', 
      controllerAs: 'vm', 
      compile: function (element, attrs) { 
       //console.log('compile'); 

       return linkFn 
      } 
     } 
    }) 
+0

或擴大範圍(範圍:真) –

+0

你」再右吧。忘記隔離指令範圍。謝謝 –

2
this.data = { 
     hello: Math.floor(Math.random() * 200 + 1) 
    } 

集data.hello僅一次(在控制器負載)。 如果你想要一個不同的結果,每次你會說:

this.data = { 
     hello: function(){ 
     return Math.floor(Math.random() * 200 + 1); 
     } 
    } 

而且隨着

ctrl.data.hello() 

工作plunkr

調用它,但是你可能想通過綁定和不通過hello功能訪問它直接從指令(更好的做法):

標記:

<custom-drv hello="hello"></custom-drv> 

指令:

.directive('customDrv', function() { 
    var linkFn = function (scope, element, attrs, ctrl) { 
     console.log('link'); 
     console.log(ctrl.hello); 
    }; 

    return { 
     template: '<h1>{{vm.hello()}}</h1>', 
     restrict: 'E', 
     scope: { 
     hello: '&' //represent function binding 
     } 
     controller: 'customCtrl', 
     controllerAs: 'vm', 
     compile: function (element, attrs) { 
      console.log('compile'); 

      return linkFn 
     } 
    } 
}) 
相關問題