sir_thursday
sir_thursday

Reputation: 5409

Directive making $scope.$watch fire twice?

I have the following $watch statement:

$scope.$watch('text', function () {
  $scope.obj = new Obj(text);
  $scope.obj.next();
});

$scope.text is the ng-model of the following input:

<input id="text" type="text" ng-model="text" name="text"/>

This works fine. However, when I abstract out the above input box along with some other HTML into a directive, the $scope.$watch chunk begins firing twice upon changes in $scope.text. Here is the directive I am abstracting out into:

myApp.directive('objDirective', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: myApp.$scope,
      controller: 'objController',
      template: '<form name="textform" id="textform">' +
                '<input id="text" type="text" ng-model="text"' +
                'name="text"/></form>',
      replace: true
    };
});

In short: $watch properly fires once when input box changes, but when input box is placed into a directive, it fires twice. Why is this?

Upvotes: 0

Views: 2560

Answers (2)

sir_thursday
sir_thursday

Reputation: 5409

Solved:

The problem was simply that I was defining both the controller in the HTML and in the directive.

Upvotes: 1

camden_kid
camden_kid

Reputation: 12813

The $watch does not fire twice in this Plunker

JS

app = angular.module("app", []);

app.directive("test", [ function() {
    return {
        restrict: "E",
        transclude: true,
        template: '<form name="textform" id="textform">' +
                '<input id="text" type="text" ng-model="text"' +
                'name="text"/></form>',
        replace: true,
        scope: app.$scope,
        controller: ["$scope", function($scope) {
          $scope.$watch("text", function(newValue) {
            if (angular.isDefined(newValue)) {
              console.log(newValue);
            }
          });
        }]
    };
}]);

Markup

<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body ng-app="app">
    <test></test>
  </body>

</html>

Upvotes: 1

Related Questions