0

我有以下$watch声明:

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

$scope.text是下面输入ng-model

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

这工作得很好。然而,当我将上面的输入框和其他一些HTML抽象成指令时,当$scope.text发生变化时,$scope.$watch块开始发射两次。这里是我从抽象到指令:

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 
    }; 
}); 

总之:在输入框的变化,但在输入框中放入指令,它触发两次$watch正确触发一次。为什么是这样?

+0

第一个可能是手表初始化(即初始手表执行),而后者当ngModel绑定空字符串时? (只是猜测) – 2015-04-04 11:32:21

+1

虽然它后面的输入框中的每次更改都会触发两次*。所以当它初始化时它会发射两次。然后当我在输入框中输入“a”时,它会发射两次。等等。 – 2015-04-04 11:33:07

+0

这行'范围:myApp。$ scope'非常奇怪且可疑。 – 2015-04-04 11:35:49

回答

1

解决:

的问题只是,我是高清在HTML中和在指令中嵌入控制器。

1

在此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); 
      } 
      }); 
     }] 
    }; 
}]); 

标记

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