简体   繁体   English

指令使$ scope。$ watch发射两次?

[英]Directive making $scope.$watch fire twice?

I have the following $watch statement: 我有以下$watch语句:

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

$scope.text is the ng-model of the following input: $scope.text是以下输入的ng-model

<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 . 但是,当我将上面的输入框以及其他一些HTML抽象到指令中时, $scope.$watch块在$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. 简而言之: $watch在输入框更改时会正确触发一次,但是在将输入框放入指令中时,它将触发两次。 Why is this? 为什么是这样?

The $watch does not fire twice in this Plunker 该$ watch在此Plunker中不会触发两次

JS 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>

Solved: 解决了:

The problem was simply that I was defining both the controller in the HTML and in the directive. 问题很简单,就是我在HTML和指令中都定义了控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM