我正在尝试从YELP获取数据 - 为了确保我的模板正常工作,我将模型附加到ng-repeat容器。这两种方法都不起作用,令我困惑的是我用$ scope.list更新我的列表,其中包含错误的数据而且没有绑定。使用某些返回的API属性也不会更新视图。有什么想法吗?
<div ng-repeat="item in list">
<div class="row">
<div class="col-lg-7 col-md-7">
<a href="#">
<img class="img-responsive" src="http://placehold.it/700x300" alt="">
</a>
</div>
<div class="col-lg-5 col-md-5">
<h3>{{item.id}}</h3>
<h4>Subheading</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae. Sed dui lorem, adipiscing in adipiscing et, interdum nec metus. Mauris ultricies, justo eu convallis placerat, felis enim.</p>
<a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
</div>
var blogAppViewController = angular.module ('blogAppViewController', []);
blogAppViewController.controller('post_View_Ctrl', function ($scope, $http, $routeParams, $location) {
$scope.list = [
{'title': 'Nexus S','name': 'Fast just got faster with Nexus S.','link':"data:wMB"},
{'title': 'Nexus S','name': 'Fast just got faster with Nexus S.','link':"data:wMB"}
];
function getYELP() {
return $.ajax({
url: '/getyelp'
});
};
/////
/////
$.when(getYELP()).done(function(results) {
this.yelp_Data = results.businesses;
$scope.list = this.yelp_Data;
console.log($scope.list);
});
});
答案 0 :(得分:1)
我看到的主要问题是你正在使用jQuery ajax请求,该请求在角度$digest周期之外运行。
因此,如果您想继续使用jQuery(虽然我建议您使用$http服务),那么您需要在修改范围值后调用$apply(),以便角度框架能够了解变化。
$.when(getYELP()).done(function (results) {
this.yelp_Data = results.businesses;
$scope.list = this.yelp_Data;
console.log($scope.list);
if (!$scope.$$phase && !$scope.$root.$$phase) {
$scope.$apply();
}
});
答案 1 :(得分:1)
(在冲浪者的声音中)“不要打角”。
尝试将您的ajax调用放入此类服务中。
<强>控制器:强>
.controller('post_View_Ctrl', function ($scope, YelpService) {
$scope.list = [
{'title': 'Nexus S','name': 'Fast just got faster with Nexus S.','link':"data:wMB"},
{'title': 'Nexus S','name': 'Fast just got faster with Nexus S.','link':"data:wMB"}
];
$scope.init = function () {
function success(value) {
$scope.list = angular.copy(value.businesses);
}
function error(reason) {
console.log(reason);
}
YelpService.get().then(success, error);
};
$scope.init();
});
<强>服务强>
.factory('YelpService', function($http, $q){
return {
get: function () {
var deferred = $q.defer();
$http.get('/getYelp')
.success(function (value) {
deferred.resolve(value);
})
.error(function (reason) {
deferred.reject(reason);
});
return deferred.promise;
}
};
})