制定$ scope的指令。$ fire fire两次?

时间:2015-04-04 11:29:28

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-service

我有以下$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.$watch块会在$scope.text的更改时开始触发两次。这是我正在摘要的指令:

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在输入框更改时正确触发一次,但当输入框放入指令时,它会触发两次。这是为什么?

2 个答案:

答案 0 :(得分:1)

$ watch在此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>

答案 1 :(得分:1)

<强>解决:

问题只是我在HTML和指令中定义了控制器。

相关问题