如何在更改模型的属性时为AngularJS创建更改指令?

时间:2013-08-29 19:18:24

标签: javascript angularjs

我试图找到解决以下问题的方法:

How to create on-change directive for AngularJS?

我已经创建了jsFiddle,它的答案是有效的...但是只有当属性直接附加到$ scope时才会出现。事实上,如果我

1)将$ scope.strText更改为$ scope.model.strText 2)并将属性值从strText更改为model.strText

不再有用了。

这里有HTML代码:

<div ng-controller="MyCtrl">
    <input on-change="model.strText"/>
    <input on-change="model.strText"/>
    <p>{{model.strText}}</p>
</div>

这里有JS代码:

var app=angular.module('myApp', []);

app.directive('onChange', function() {    
    return {
        restrict: 'A',
        scope:{'onChange':'=' },
        link: function(scope, elm, attrs) {            
            scope.$watch('onChange', function(nVal) { elm.val(nVal); });            
            elm.bind('blur', function() {
                var currentValue = elm.val();                
                if( scope.onChange !== currentValue ) {
                    scope.$apply(function() {
                        scope.onChange = currentValue;
                    });
                }
            });
        }
    };        
});

app.controller('MyCtrl', function($scope) { 
    $scope.model.strText = "Hello";
});

这里有jsFiddle

http://jsfiddle.net/pmcalabrese/XbJVb/

提前谢谢。

1 个答案:

答案 0 :(得分:2)

由于$scope.model未定义,因此您的数据源存在一些缺陷。将其更改为

app.controller('MyCtrl', function ($scope) {
    $scope.model = {};
    $scope.model.strText = "Hello";
});