我无法弄清楚如何为 AngularJS 中的指令创建与模板内元素的双向绑定(bind)。
我的例子:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<input ng-model="myValue" />{{myValue}}
<uppercase ng-model="myValue" />
</div>
</div>
Javascript
var app = angular.module('App', []);
function AppCtrl($scope) {
$scope.myValue = 'Hello World';
};
app.directive('uppercase', function() {
return {
restrict : 'E',
replace: true,
require: 'ngModel',
template: '<div><input ng-model="ngModel" /></div>', //If I remove the wrapping div, it works, but I have to change the ng-model attribute on the directive scope to be something else, such as 'model'
scope: {
ngModel: '=',
},
link: function(scope, element, attr, ngModel) {
function parse(string) { //with the div in the template function is never called
//alert('parsing');
//debugger;
return (string || '').toLowerCase();
}
function format(string) { //with the div in the template, string is always 'undefined' and the function is only called once
//alert('formatting');
//debugger;
return (string || '').toUpperCase();
}
ngModel.$parsers.push(parse);
ngModel.$formatters.push(format);
}
};
});
问题在于双向绑定(bind)已建立,但解析器和格式化程序未正确调用。传递给这些函数的值始终是“未定义”的。如果我要绑定(bind)的元素是模板中最外层的元素,我的示例将起作用,但我需要绑定(bind)到子元素。
我想我已经将问题范围缩小到了链接函数中 ngModel 参数的问题。我对指令不太熟悉,所以我什至不确定 ngModel 对象在该上下文中是什么。
任何调试此问题的帮助将不胜感激。
最佳答案
这种指令作为使用 ng-model 指令修改元素的属性效果更好。这可以让你摆脱所有的模板。
<div ng-app="App">
<div ng-controller="AppCtrl">
<input ng-model="myValue" />{{myValue}}
<input uppercase ng-model="myValue" />
</div>
</div>
关于javascript - 在 AngularJS 中使用解析器和格式化程序在指令模板中执行双向绑定(bind)时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116418/