我正在创建我的第一个指令,我遇到了一些奇怪的行为。我的链接函数中的 console.log()被调用了两次。我在谷歌上搜索了一些解决方案,但是我不知道如何修改代码来改变行为.
我的index.html:
<html>
<head>
<title>GCSE Directive TEST</title>
</head>
<body ng-app="gcseTest">
<google-image-search query="Test query"></google-image-search>
<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="gcse-directive.js"></script>
</body>
</html>gcse-指令:
angular.module('gcseTest', [])
.directive('googleImageSearch', [ function(){
return {
scope: {
query: '@'
},
templateUrl: 'gcse-popup.html',
restrict: 'E',
replace: true,
link: function ($scope, $element, $attrs) {
$scope.search = function(){
console.log("Gebruik query in link-functie: " + $scope.query);
return "Gebruik query via popup: " + $scope.query;
}
}
};
}]);gcse-popup.html:
<div>
<h1>Directive Test</h1>
{{search(query)}}
</div>有人能解释一下这是怎么回事吗?
发布于 2017-06-25 19:25:02
您的指令链接函数不会被调用两次,它的search函数将被调用两次。它背后的原因是被调用了两倍,您已经直接使用了search函数,就像在视图绑定中一样,所以每当摘要周期运行时,您的视图绑定都会得到评估。在本例中,摘要周期被运行了两次,这就是为什么您的search函数运行了两次,并且您可以看到console打印了两次。
https://stackoverflow.com/questions/44749513
复制相似问题