我有一个指令,该指令的 Controller 带有对端点的 $http 调用。我想获取该服务器调用的结果,然后将它们显示在我的模板中。如果我的模板中有一个值,然后显式设置它,则一切正常。如果我尝试将模板绑定(bind)到服务器调用,则会收到上述错误。我需要使用 $compile 服务才能正常工作吗?
提前致谢
编译最终结果
function mydirective(myservice,$compile) {
return {
restrict: 'ACE',
scope: {
url: '=',
title: '=',
},
controllerAs: 'ctrl',
bindToController: true,
controller: ['$scope', function($scope) {
myservice.init('http://jsonplaceholder.typicode.com/posts')
.then(function(data) {
$scope.postRequest(data);
});
$scope.postRequest = function(val) {
this.items = val;
this.title = val[0].title;
};
}],
link: function ($scope, $el, $attr ) {
var template = '<div class=\"test\">{{this.title}}</div>' +
'<div class=\"tes\" ng-repeat=\"item in this.items\">'+
'<div class=\"test1\">{{item.title}}</div>'+
'</div>';
var e = $compile(template)($scope);
$el.after(e);
}
};
}
最佳答案
这是您的指令的重构版本。由于您使用的是 controllerAs
,因此可以完全删除对 $scope
的引用。此外,还创建了一个变量 ctrl 作为 Controller 的别名,以便从回调函数内部对 Controller 进行一致的访问。最后,删除了 link
函数,并将 template
调整为引用 ctrl
而不是 this
。
错误
RangeError: Maximum call stack size exceeded
是在模板中使用this
的结果,它指的是DOM而不是 Controller ,与$compile
结合使用,本质上是将DOM编译到自身中.
function mydirective(myservice, $compile) {
return {
restrict: 'ACE',
scope: {
url: '=',
title: '=',
},
controllerAs: 'ctrl',
bindToController: true,
controller: function() {
var ctrl = this; //alias reference for use inside controller callbacks
myservice.init('http://jsonplaceholder.typicode.com/posts')
.then(function(data) {
ctrl.postRequest(data);
});
ctrl.postRequest = function(val) {
ctrl.items = val;
ctrl.title = val[0].title;
};
},
template: '<div class=\"test\">{{ctrl.title}}</div>' +
'<div class=\"tes\" ng-repeat=\"item in ctrl.items\">' +
'<div class=\"test1\">{{item.title}}</div>' +
'</div>'
};
}
请注意此代码尚未经过测试。
关于javascript - Angular 1- Angular .js :11655 RangeError: Maximum call stack size exceeded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37890337/