AngularJS 不停地调用 http get 请求!!
如果我直接在 Controller 中调用 getContexts 就没问题...但如果我从 html 模板
调用它,它只会继续调用 get。
部分contextCtrl.js:
'use strict';
app.controller('ContextCtrl', function ContextCtrl($scope, $location, $http, $rootScope, ContextService) {
$scope.getContexts = function(keys)
{
$scope.contexts = {};
$http.get('/getContextsWS?keys=' + keys).
success(function(data){
$scope.contexts = data;
});
}
// This works
$scope.getContexts('["context::one", "context::two"]')
});
部分 html 部分:
<section id="contextSection" ng-controller="ContextCtrl">
// This causes get to keep calling!
{{getContexts('["context::one", "context::two"]')}}
// Just checking
{{contexts|json}}
<nav>
<ul ng-show="contexts.length" ng-cloak>
<li ng-repeat="context in contexts">
<div class="view" ng-click="contextSelected(context)">{{context.name}}</div>
</li>
</ul>
</nav>
</section>
这让我抓狂!
好吧,我已经尝试了你的隐藏字段示例,但我似乎无法让它工作,但也许我遗漏了什么......
html:
<section id="contextSection" ng-controller="ContextCtrl">
<input type="hidden" ng-model="contextIds" copy-to-model value='@product.item.contextIds'/>
指令:
mto.directive('copyToModel', function ($parse) {
return function (scope, element, attrs) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
});
Controller :
app.controller('ContextCtrl', function ContextCtrl($scope, $location, $http, $rootScope, ContextService) {
// I can read this, but it never changes, and without this the contextIds in the alert are null
$scope.contextIds = "...";
$rootScope.alert = function(text)
{
alert(text);
}
$rootScope.alert("$scope.contextIds: " + $scope.contextIds);
});
知道我做错了什么吗?
最佳答案
您的 {{ }}
绑定(bind)代码中的表达式将在任何时候 Angular 注意到模型中的某些内容发生变化时重新计算(我已经过分简化了实际发生的事情)。如果您只想调用一次 getContexts
,请不要将其放在标记中的 {{ }}
中,而只需在您的 Controller 代码中调用即可。
基本上假设 {{ }}
中的代码可以并且将会被多次调用..
所以尝试删除:
// This causes get to keep calling!
{{getContexts('["context::one", "context::two"]')}}
并依赖于您的 Controller 代码(如果您不从您的标记中调用它,您可能不希望在您的范围内使用 getContexts
):
// This works
$scope.getContexts('["context::one", "context::two"]')
关于http - AngularJS 不断从 html 模板调用 $http.get,而不是从 Controller 内部调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12944135/