当我从服务电话回来时,我似乎无法更新我的观点。为什么'没有破坏'永远不会被推到控制台?
服务返回 [{test:'service workies'}]
app.controller('foo-controller', ['fooService','$scope', function (fooService,$scope) {
var ctrl = this;
ctrl.Results = [{ test: 'no workies' }];
ctrl.Search = function () {
fooService.GetFoos().then(function (result) {
console.log('test');
console.log(ctrl.Results);
ctrl.Results = result;
console.log(ctrl.Results);
$scope.$apply(function () {
console.log('not broken');//never fires!!
ctrl.Results = [{test : 'workies' }]
});
});
};
return ctrl;
}]);
app.directive('fooLogo', function () {
return {
restrict: 'E',
templateUrl: './App/Templates/foo.html',
controller: 'foo-controller',
controllerAs: 'f'
};
});
编辑foo服务
.service('fooService', ['$http', function ($http) {
return $http.get("https://www.googleapis.com/books/v1/volumes?q=harry+potter").then(
function(result){ return [{ test: 'service workies'}]},
function(error) { return [{test: 'service call no workies'}] );
答案 0 :(得分:2)
我在您的代码中看到了一些问题。我在fooService
内的任何地方都看不到宣布GetFoos()
的地方,因此这是一个问题。请尝试以下方法:
app.controller('MainCtrl', ['$scope', 'BookQueryService',
function($scope, BookQueryService) {
$scope.search = function() {
BookQueryService.getBooks().then(function(data) {
$scope.books = data.data.items;
});
};
// call immediately for the sake of this example
$scope.search();
}
]);
app.service('BookQueryService', ['$http',
function($http) {
var service = {};
service.getBooks = function() {
return $http.get("https://www.googleapis.com/books/v1/volumes?q=harry+potter");
};
return service;
}
]);
app.directive('myBookList', function() {
return {
restrict: 'E',
templateUrl: 'BookList.html',
controller: 'MainCtrl'
}
});
使用以下html:
<body>
<my-book-list></my-book-list>
</body>
以下指令模板:
<div>
<ul>
<li data-ng-repeat="book in books">
{{book.volumeInfo.title}}
</li>
</ul>
</div>
这里有一个带有工作示例的傻瓜: http://plnkr.co/edit/KJPUWj0ghDi1tyojHNzI?p=preview
答案 1 :(得分:0)
fooService.GetFoos().then(function(result){...})
内的任何内容都在运行吗?如果您发布的代码全部是fooService
,那么看起来似乎没有.GetFoos
方法&amp;因此,以下.then
内的任何内容都无法运行。
尝试在链接到.error
的原始.then
之后添加fooService.GetFoos
:
fooService.GetFoos().then(function (result) {
// your code
}).error(function (data, status){
console.log("Error!\t", status);
};
这将帮助您弄清楚到底发生了什么。每当您使用任何类型的承诺时,请确保您拥有.catch
或.error
- 它们可以在调试时为您节省大量麻烦。查看有角度的$http
documentation了解更多详情。
此外,看起来对$scope.$apply()
的原始呼叫是不必要的。如果你想运行一个超出角度的函数,或者你手动想要触发摘要周期,那么你只会使用它(如果是这种情况,那么明确地调用$scope.$digest()
会比$scope.$apply
更合适。
查看此blog post,了解何时使用$scope.$apply
和$scope.$apply
documentation page了解更多信息