我已经绑定了一个带有 ng-click 事件的按钮,该事件会在我的控制器上触发一个函数。这再次使用 $http 获取一些数据,并且效果很好。但是在成功回调中更新我的模型时,UI 不会更新。我试过使用 $scope.$apply 和 $scope.safeApply 没有运气。UI 中什么也没有发生。从服务返回数据。请参阅下面的代码。
搜索控制器:
'use strict';
searchApp.controller('SearchController',
function SearchController($scope, searchData) {
$scope.query = '';
$scope.isLoading = false;
$scope.result = null;
$scope.doSearch = function () {
$scope.isLoading = true;
searchData.getSearchResult($scope.query, function (result) {
$scope.safeApply(function() {
$scope.result = result;
console.log($scope.result);
});
});
};
$scope.safeApply = function (fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && (typeof (fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
}
);
HTML 标记:
<div class="search-result" ng-controller="SearchController">
<input type="text" value="Enter query..." ng-model="query" />
<input type="button" value="Search" ng-click="doSearch()" />
<div ng-show="isLoading">
Searching....
</div>
<h2>{{ result.SearchGroups }}</h2>
<div class="result-box" ng-repeat="group in result.SearchGroups">
<div class="head">
<h2>{{ group.Name }}</h2>
<!--<span class="seeAll">Se alle (13)</span>-->
</div>
<div class="body">
</div>
</div>
</div>