请参阅下面的代码。在我看来,我很难展示$scope.brand的价值。当我单击获取用户品牌按钮时,没有任何反应。视图中的 brand.name 未更新,但是当我单击"获取用户品牌"按钮后单击测试品牌按钮时,将显示范围的值。我不知道现在发生了什么。请帮忙。谢谢!
角
var app = angular.module('nwApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
var url = 'http://localhost:3000';
app.controller('brandsCtrl', ['$scope', '$http', function($scope, $http){
$scope.brands = {};
$scope.brand = {};
$http.get(url+'/brands/all')
.success(function(result){
$scope.brands = result;
});
$scope.getAssignUser = function(brand_id){
$.get(url+'/brands/'+brand_id)
.success(function(result){
$scope.brand = result;
});
$("#brandModal").modal('toggle');
};
$scope.checkBrand = function(){
console.log($scope.brand);
}
}]);
视图
<a href="javascript:void(0)" class="btn btn-warning" title="Assign User for this Brand" ng-click='getAssignUser(brand._id)' >GET USER BRAND</a>
<a href="javascript:void(0)" class="btn btn-warning" ng-click='checkBrand()' > TEST BRAND </a>
<div><% brand.name %></div>
问题就在这里:
$.get(url+'/brands/'+brand_id)
.success(function(result){
$scope.brand = result;
});
$.get
是jquery,所以当它成功更新$scope.brand时,摘要周期将不会运行并反映值。
你应该利用 angular 提供的$http
服务来做 ajax:
$http({
method: 'GET',
url: url+'/brands/'+brand_id
}).then(function successCallback(result) {
$scope.brand = result;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
其他解决方案是:
在 jquery ajax 中,您可以像这样更改$apply
内部的作用域变量:
$.get(url+'/brands/'+brand_id)
.success(function(result){
$scope.$apply(function (){$scope.brand = result;});
});