[英]Assigning a controller from a directive angularjs 1.2
我從angularJS 1.0切換到1.2,在將控制器分配給具有干凈作用域的指令時遇到了一些麻煩,而沒有在ng-controller的html中定義控制器。
請考慮以下情形:
var myApp=angular.module('myApp',[])
.controller('parentCtrl',function($scope,$element,$attrs) {
$scope.helloworld = function(){
console.log('hello world from ParentCtrl controller')
}
})
.controller('childCtrl',function($scope,$element,$attrs) {
$scope.helloworld = function(){
console.log('hello world from ChildCtrl controller')
}
})
.directive('ngParent', function() {
return {
controller:'ParentCtrl'
}
})
.directive('ngChild', function() {
return {
controller:'ChildCtrl',
scope:{},
link:function(scope,element,attrs){
}
}
})
和HTML:
<body ng-app="myApp" ng-parent>
<button ng-click="helloworld()">Parent Scope click </button>
<div ng-child>
<button ng-click="helloworld()">Child Scope click </button>
</div>
</body>
現在,這兩個按鈕都將記錄“來自ParentCtrl控制器的Hello world”。 但是,如果我在ngChild指令中將參數scope:{}更改為scope:true,它將起作用,並且按鈕正在調用各自范圍的helloworld函數。 但是,這並沒有達到我想要的范圍。
我如何在角度1.2的指令中創建干凈的作用域,而不在我的視圖中分配控制器?
謝謝,安德里亞斯
因為您沒有創建新的作用域,所以兩個指令都使用相同的作用域,並且“ helloworld”函數的定義將被覆蓋。 因此,您需要更改函數名稱或創建新的作用域,
順便說一句,我認為您使用的指令是錯誤的。 與其定義指令並為其分配控制器,不如使用ng-controller,並且為每個控制器在自己的范圍內設置helloworld函數。 並編寫指令(如果確實需要)以獲取該函數並在需要時調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.