pm.calabrese
pm.calabrese

Reputation: 376

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

I was trying to find a solution to the following problem:

How to create on-change directive for AngularJS?

And i've founded, the jsFiddle in the answer it works...but only if the property is attached directly to the $scope. In fact if i

1) change $scope.strText to $scope.model.strText 2) and change the attribute values from strText to model.strText

does not work anymore.

here there is the HTML code:

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

and here there is the JS code:

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";
});

Here there is the jsFiddle

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

Thank you in advance.

Upvotes: 0

Views: 995

Answers (1)

zs2020
zs2020

Reputation: 54543

Your data source has some flaw since $scope.model is undefined. Change it to

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

Upvotes: 2

Related Questions