Controller :
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
内部> 函数打印正确。
最佳答案
您正在尝试将模板中的指令范围作为 Controller 的范围进行访问。将标记移至指令模板内。
指令:
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 文件作为指令模板,这是一个很好的做法。
关于javascript - 如何从 Angular 中的静态指令模板访问隔离范围属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39912051/