我有以下$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/