0

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.

1 Answer 1

2

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";
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.