user448283
user448283

Reputation: 69

angularjs custom directive two way binding watch not working

I created a custom directive and am using two way binding (=)

But I want to watch changes in controller when model is changed in directive.

alert should appear when user changes input but alert appears only one time at the beginning.

My javascript

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

    .controller("myCtrl", function ($scope) {
    $scope.test = "myValue";
    $scope.$watch('myValue', function () {
        alert('hey, myVar has changed!');
    });
})

    .directive('myDirective', function () {
    return {
        restrict: 'EA',
        scope: {
            myModel: '=ngModel'
        },
        template: '<input ng-model="myModel"/>'
    }
});

and html

<div ng-app="myApp">
    <div ng-controller="myCtrl">{{test}}
        <my-directive ng-model="test"></my-directive>
    </div>
</div>

http://jsfiddle.net/c7nbk8uq/

Upvotes: 1

Views: 349

Answers (2)

Rasalom
Rasalom

Reputation: 3111

You misspelled 'myValue' and 'test'.

 $scope.$watch('test', function() {
       alert('hey, myVar has changed!');
   });

http://jsfiddle.net/pmydr7qp/

Upvotes: 1

Joao Leal
Joao Leal

Reputation: 5542

You are watching the wrong variable?

$scope.$watch('test', function() {
       alert('hey, myVar has changed!');
   });

Upvotes: 1

Related Questions