javascript - 在 AngularJS 中使用解析器和格式化程序在指令模板中执行双向绑定(bind)时出现问题

标签 javascript angularjs angularjs-directive

我无法弄清楚如何为 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);
    }
};    
});

http://jsfiddle.net/DuHvy/7/

问题在于双向绑定(bind)已建立,但解析器和格式化程序未正确调用。传递给这些函数的值始终是“未定义”的。如果我要绑定(bind)的元素是模板中最外层的元素,我的示例将起作用,但我需要绑定(bind)到子元素。

我想我已经将问题范围缩小到了链接函数中 ngModel 参数的问题。我对指令不太熟悉,所以我什至不确定 ngModel 对象在该上下文中是什么。

任何调试此问题的帮助将不胜感激。

最佳答案

http://jsfiddle.net/DuHvy/8/

这种指令作为使用 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/

相关文章:

angularjs - ngShow 无法在 HTML 上使用模板

javascript - 如何使用 AngularJs 刷新 Ng-repeat

javascript - 如何在指令 AngularJS 之间传递对象?

javascript - 表单提交时在浏览器中显示加载

javascript - Flash CC - HTML5 Canvas : Slideshow Navigation

angularjs - 在具有隔离范围的嵌套指令中延迟双向绑定(bind)

javascript - AngularJS - Firebase重置密码更改没有得到反射(reflect)

javascript - 获取值并将其传递给按钮

javascript - 水平平移 D3.js

javascript - 从 bower 中删除依赖项