繁体   English   中英

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

[英]How to create on-change directive for AngularJS when change a property of a model?

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

如何为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/

先感谢您。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM