[英]Have a dynamic html element using AngularJS Directive WHITOUT $scope?
我想使用This Plunker示例代碼使用AngularJS將一些元素動態添加到HTML頁面。 ( 您應該在新的鏈接中運行它,而不是在編輯器環境中運行 )這是我在聲明AngularJS指令時的第一次經驗(簡單測試除外)。 關於此示例,我有兩個問題:
Controller as
中使用Controller as
而不是$Scope
。 (我不知道這種方法的名稱!)那么我應該如何使用上面的示例代碼? 因為它使用$compile(...)($scope)
。 應該應用哪些更改? 1)當使用contrller作為語法時,對於$compile(...)($scope)
更改為$compile(...)(vm)
。 並且對於所有函數和變量,而不是$ scope使用vm
或this
var vm = this;
所以不是$scope.list
使用vm.list
和功能也可以使用。
$scope.do = function() ..
vm.do = function() ....
2)在指令中添加controllerAs
像這樣
app.directive('myDirective', function () {
return {
scope: {},
controller: function () {
this.name = 'Elnaz'
},
controllerAs: 'ctrl',
template: '<div>{{ctrl.name}}</div>'
};
});
如果要引用外部控制器,請使用此
app.directive('myDirective', function () {
return {
restrict: 'A',
controller: 'EmployeeController',
controllerAs: 'ctrl',
template: ''
};
});
在您看來,更改如下:
<div ng-controller="myController as ctrl">
{{ctrl.name}}
<button type="button" ng-click="ctrl.do()">Do</button>
</div>
編輯: 作品演示
回答您的第一點:
在控制器內部,您將創建一個變量來表示“ controller as”;
var vm = this;
現在綁定到$ scope的所有屬性現在將成為vm的一部分
<div ng-controller="customCntrl as vm"
在指令中:將控制器與“ controller as”綁定的方式:
app.directive('customDir',function(){return {controller:'customCntrl',controllerAs:'vm',...
} });
對第二點的回答:
您仍然可以像這樣應用廣播並通過'vm'發出:
$ scope。$ watch('vm.name',function(){$ scope。$ broadcast('topic-123','msg');});
並捕獲它:$ scope。$ on('topic-123',function(event,msg){});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.