Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $scope.$watch on json object not working inside directive

Tags:

angularjs

I'm missing something obvious here. In my directive I have a working two-way data binding however I can't seem to use $scope.$watch() to monitor changes which may occur on the directive's parent scope js object.

http://jsfiddle.net/Kzwu7/6/

As you can see, when I try to use $watch on attrs.dirModel the resulting value is undefined and nothing is further watched, even though I'm modifying the object after a brief delay. I've also tried using (and not using) the true flag on the $watch statement.

HTML:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>

<div ng-app="test" ng-controller="MainCtrl">
    <dir dir-model="model"></dir>
    <p>{{model.tbdTwoWayPropA}}</p>
</div>

<script type="text/ng-template" id="template">
    <div class="test-el">{{dirModel.tbdTwoWayPropB}}</div>
</script>

JS:

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

app.controller("MainCtrl", [
    "$scope", "$timeout",
    function($scope, $timeout){
        $scope.model = {
            tbdTwoWayPropA: undefined,
            tbdTwoWayPropB: undefined,
            tbdTwoWayPropC: undefined
        }

        // TBD Ajax call
        $timeout(function(){

            // alert("Model updated, but $scope.$watch isn't seeing it.");

            $scope.model.tbdTwoWayPropA = 1;
            $scope.model.tbdTwoWayPropB = 30;
            $scope.model.tbdTwoWayPropC = [{ a: 1 },{ a: 2 },{ a: 3 }];

        }, 2000)
    }
]);

app.directive('dir', [
  "$timeout",
  function($timeout) {
      return {
          restrict: "E",
          controller: function($scope){
              $scope.modifyTwoWayBindings = function(){

                  // Two-way bind works
                  $scope.dirModel.tbdTwoWayPropA = 2;
              }

              $timeout(function(){
                  $scope.modifyTwoWayBindings();
              }, 4000);
          },
          scope: {
              dirModel: '='
          },
          template: $("#template").html(),
          replace: true,
          link: function($scope, element, attrs) { 

            $scope.$watch( attrs.dirModel, handleModelUpdate, true);

              // alert(attrs.dirModel);

              function handleModelUpdate(newModel, oldModel, $scope) {
                  alert('Trying to watch mutations on the parent js object: ' + newModel);
              }
          }
      }
}]);
like image 997
BradGreens Avatar asked Mar 11 '13 17:03

BradGreens


1 Answers

Since you are using '=', you have a local directive scope property dirModel. Just $watch that:

$scope.$watch('dirModel', handleModelUpdate, true);
like image 104
Mark Rajcok Avatar answered Sep 17 '22 20:09

Mark Rajcok