[英]How to access isolated scope property from static directive template in Angular?
控制器:
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.temp = {
'name': 'Test'
};
}]);
模板:
<custom-field ng-model="temp.name">
<md-input-container class="addon-menu">
<label>Name</label>
<input ng-model="ngModel" type="text" ng-focus="setLastFocusedElement($event)" />
</md-input-container>
</custom-field>
指示:
app.directive('customField', function($timeout) {
return {
restrict: 'E',
scope: {
ngModel: '='
},
link: function($scope, $element, $attrs) {
console.log($scope.ngModel); // prints "test"
}
};
});
問題在於,一旦呈現了模板,我將看不到input
附加的值-它為空,但是我希望它能正常工作,因為在link
函數內部它可以正確打印。
您正在嘗試訪問模板中的指令范圍作為控制器的范圍。 而是將標記移動到指令的模板內。
指示:
app.directive('customField', function($timeout) {
return {
restrict: 'E',
scope: {
ngModel: '='
},
link: function($scope, $element, $attrs) {
console.log($scope.ngModel); // prints "test"
},
template: '<md-input-container class="addon-menu"><label>Name</label><input ng-model="ngModel" type="text" ng-focus="setLastFocusedElement($event)" /></md-input-container>'
};
模板:
<custom-field ng-model="temp.name"></custom-field>
您也可以將單獨的html文件用作指令模板,這是一個很好的實踐。
您是否正在嘗試查看控制器中的值?
請嘗試$ parent。$ scope以查看值是否存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.