我尝试使用Angular Material md-autocomplete
,通过 Ajax Call 从服务主机检索建议列表。由于延迟响应,$scope
变量未正确更新UI ,因此仅在特定控件中发生任何事件时才更新。对于示例焦点已发送并再次单击控件,然后使用新值更新UI。
我的确切问题快照发布在md-items is not updating the suggesion list properly in md-autocomplete Angular Material
经过很长一段时间的谷歌我得到了理论解决方案$scope.$apply()
- 参考来自Angular controller scope not updating after jQuery ajax call
但我收到错误错误:[$ rootScope:inprog] ... 请帮我解决错误
完整示例源代码:
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Person to Select:</p>
<md-autocomplete
ng-disabled="isDisabled"
md-no-cache="noCache"
md-selected-item="selectedItem"
md-search-text-change="searchTextChange()"
md-search-text="searchText"
md-selected-item-change="selectedItemChange(item)"
md-items="item in Person"
md-item-text="item.Name"
md-min-length="0"
placeholder="Which is your favorite Person?">
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.Name}} - {{item.City}}</span>
</md-item-template>
<md-not-found>
No Person matching "{{searchText}}" were found.
</md-not-found>
</md-autocomplete>
<br/>
</div>
<script>
var app = angular.module('myApp', ['ngMaterial']);
app.controller('myCtrl', function ($scope, $http, $q) {
$scope.searchText = "";
$scope.Person = [];
$scope.selectedItem = [];
$scope.isDisabled = false;
$scope.noCache = false;
$scope.selectedItemChange = function (item) {
alert("Item Changed");
}
$scope.searchTextChange = function () {
$http({
method: "GET",
url: "http://www.w3schools.com/angular/customers_mysql.php",
params: {
uid: $scope.searchText
}
})
.then(function (response) {
$scope.$apply(function () {
$scope.Person = response.data.records;
});
});
}
});
</script>
</body>
</html>
&#13;
实际上我使用localhost进行ajax调用,在这里我提到示例Ajax URL是http://www.w3schools.com/angular/customers_mysql.php,供您参考以获取数据。
注意:我需要在Ajax调用中使用
$scope.$apply()
而不会出现错误错误:[$ rootScope:inprog] ...
请帮助我......如何解决。
浏览器快照
答案 0 :(得分:2)
$scope.$apply
函数时,Angular会自动调用 $
,因此您不必自己调用它,您的UI未更新的原因必须在其他地方。
答案 1 :(得分:1)
如果您需要这样做,请尝试$scope.$applyAsync
文档here。
答案 2 :(得分:1)
Angular通常在内部调用$ digest,$ watch来绑定范围变量。
在您的情况下,您必须手动调用任何事件侦听器来绑定数据值。
尝试在范围变量中使用$ watch或$ apply
function Ctrl($scope) {
$scope.messageToUser = "You are done!";
setTimeout(function () {
$scope.$apply(function () {
$scope.messageToUser = "Timeout called!";
});
}, 2000);