[英]Angular 1.5: Access bindToController properties inside controller
我正在學習如何正確使用自定義指令的 bindToController 功能,並想知道如何從指令控制器訪問您在 bindToController 對象中聲明的屬性。
var myApp = angular.module('myApp',[])
.directive('myDir', MyDir)
.controller('MyCtrl',['$scope', MyCtrlFn]);
function MyCtrlFn($scope) {
var ctrl = this;
this.ctrlStr = '';
this.ctrlAsStr = '';
$scope.$watch(this.name, function(newValue) {
if(newValue) ctrl.ctrlStr += ' '+newValue;
})
$scope.$watch('ctrl.name', function(newValue) {
if(newValue) ctrl.ctrlAsStr += ' '+newValue;
})
}
function MyDir() {
return {
template: '<div>{{ctrl.name}}</div>'+
'<div>CtrlStr: {{ctrl.ctrlStr}}</div>'+
'<div>CtrlAsStr: {{ctrl.ctrlAsStr}}</div>',
scope: {},
bindToController: {
name: '='
},
restrict: 'E',
controller: 'MyCtrl',
controllerAs: 'ctrl'
}
}
jsFiddle在這里: http : //jsfiddle.net/jrtc1bLo/2/
所以我認為屬性綁定到控制器,但似乎它們綁定到范圍內的控制器別名。
從控制器訪問它們的好方法是什么?
謝謝
如果您更正第一個觀察者,您將看到您的控制器已正確綁定。
function MyCtrlFn($scope) {
var ctrl = this;
this.ctrlStr = '';
this.ctrlAsStr = '';
//DO THIS
$scope.$watch(function(){return ctrl.name}, function(newValue) {
// NOT THIS
//$scope.$watch(this.name, function(newValue) {
if(newValue) ctrl.ctrlStr += ' '+newValue;
})
$scope.$watch('ctrl.name', function(newValue) {
if(newValue) ctrl.ctrlAsStr += ' '+newValue;
})
}
$watch
的第一個參數要么是一個在每個摘要周期評估的函數,要么是一個字符串形式的 Angular 表達式,它在每個摘要周期評估。
通過更正,兩個觀察者都會看到變化。
看看這個例子:
angular
.module('form')
.controller('FormGroupItemController', FormGroupItemController)
.directive('formGroupItem', formGroupItem);
function FormGroupItemController(){}
function formGroupItem() {
var directive = {
restrict: 'A',
scope: {
model: '=',
errors: '=',
submit: '='
},
bindToController: true,
controller: 'FormGroupItemController as vm',
templateUrl: 'app/form/form-group-item.html'
};
return directive;
}
如您所見,我有一個form-group-item
指令。 我在我的 HTML 中使用它,如下所示:
<div form-group-item model="vm.username" errors="vm.errors" submit="vm.updateUsername"></div>
在這里,我從指令使用的范圍中提取了三樣東西,我基本上復制了指令本身的它們(將它們綁定到控制器)。 這三件事是:模型、錯誤和提交。
錯誤是一包可能的錯誤(數組),模型只是一個要觀察的值,提交是一個提交函數。
現在這三件事都在FormGroupItemController
的范圍內,我可以在form-group-item.html
用作$scope
或controllerAs
,無論我指定哪個。 在這種情況下,我使用 controllerAs 語法。
所以在指令綁定到它的控制器之前,它只是一個像這樣的空構造函數:
function FormGroupItemController() {}
綁定后,它將如下所示:
function FormGroupItemController() {
this.model = 'blah';
this.errors = [...];
this.submit = function(...) {...}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.