[英]ng-change doesn't update view AngularJS
我正在研究AngularJS,并尝试使用加载产品。
$scope.update=function(){
$scope.loading = true;
$scope.brandString=$scope.brands.join(':');
UpdateService.getProducts($scope).then(function (data) { $scope.loading = false; $scope.products = data.Products;}, function () {
});
};
$scope.changepage=function(pagenum){
$scope.pagenumber=pagenum;
$scope.update();
};
$scope.changeorderby=function(orderby){
$scope.orderby=orderby;
$scope.pagenumber=1;
$scope.update();
};
$scope.updatebrands=function(id){
var index = $scope.brands.indexOf(id);
// Add if checked
if ($('#'+id).is(':checked')) {
if (index === -1) $scope.brands.push(id);
}
// Remove if unchecked
else {
if (index !== -1) $scope.brands.splice(index, 1);
}
$scope.update();
};
我的第二和第三功能,即changepage
和changeorderby
正常工作,并且也更新了视图。 复选框更改时被调用的第四个函数也从服务器返回正确的数据,但不会更新我的视图。
复选框代码。
<div class="listbox">
<ul>
<div ng-class="{active : item.Checked, inactive:!item.Checked}" ng-repeat="item in brandDetails" style="padding:1px 0">
<div ng-class="{divchecked : item.Checked, divunchecked:!item.Checked}">
<input type="checkbox" id="{{item.Id}}" ng-change="updatebrands(item.Id)" ng-model="item.Checked" name="{{item.Name}}" value="{{item.Id}}" style="opacity:0" class="brandName ng-pristine ng-valid" /></input>
</div>
<span style="margin-left: 8px; font-size: 11px;top: -1px;position: relative;">{{item.Name}}</span>
</div>
</ul>
</div>
我在这里想念的是什么?
如果UpdateService.getProducts()
使用原始的角度$ http服务,则角度将不知道发生了什么事,因此您需要调用$scope.$apply()
$scope.update = function(){ $scope.loading = true; $scope.brandString = $scope.brands.join(':'); UpdateService.getProducts($scope).then(function (data) { $scope.loading = false; $scope.products = data.Products; // Only if UpdateService.getProducts isn't pure $http or $q service $scope.$apply(); }, function () { // error }); }; $scope.changepage = function(pagenum){ $scope.pagenumber = pagenum; $scope.update(); }; $scope.changeorderby = function(orderby){ $scope.orderby = orderby; $scope.pagenumber = 1; $scope.update(); }; $scope.updatebrands = function(item){ var index = $scope.brands.indexOf(item.id); // Add if checked if (item.Checked) { if (index === -1) $scope.brands.push(item.id); } // Remove if unchecked else { if (index !== -1) $scope.brands.splice(index, 1); } $scope.update(); };
<div class="listbox"> <ul> <li> <div ng-class="{active : item.Checked, inactive: !item.Checked}" ng-repeat="item in brandDetails" style="padding: 1px 0"> <div ng-class="{divchecked : item.Checked, divunchecked: !item.Checked}"> <input type="checkbox" id="{{item.Id}}" ng-change="updatebrands(item)" ng-model="item.Checked" name="{{item.Name}}" style="opacity: 0" class="brandName ng-pristine ng-valid" /> </div> <span style="margin-left: 8px; font-size: 11px; top: -1px;position: relative;">{{item.Name}}</span> </div> </li> </ul> </div>
(顺便说一句,您的代码仍然有几个问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.