javascript - 指令使 $scope.$watch 触发两次?

标签 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 block 会根据 $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 会正确触发一次,但是当输入框放入指令中时,它会触发两次。这是为什么?

最佳答案

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

关于javascript - 指令使 $scope.$watch 触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29445862/

相关文章:

javascript - 选择下拉菜单上的 ng-change 和 ng-repeat 仅触发一次

object - 如何获取在 angularjs 中更改的对象?

javascript - 获取具有动态列数的表的最后一行、最后一列的值

javascript - 必需 ||必需的 HTML5 表单

javascript - 以编程方式为 Facebook 搜索输入赋予值(value),以便它返回建议框

javascript - 当输入值无效时如何禁用按钮

javascript - 如何在 Angular js 中包含模块以删除未找到模块的错误?

javascript - 在 Angular : are the compile function's pre and post methods the same as link's pre and post

javascript - 如果没有 $evalAsync inside 指令,$animate.removeClass 无法工作?

javascript - 使用标签 data-* 实现 Ajax 调用