[英]AngularJS $scope updates not reflected in the view
首先,很抱歉讓我感到困惑,但是整個晚上我都在解決這個問題,而且我已經閱讀了許多SO問題和AngularJS文章,所以現在我不確定是否知道問題出在哪里:)
我有一個ng-app,在控制器中,當我為$scope
幾個屬性定義默認數據時,當此數據稍后以編程方式更改時,視圖將停止更新。
這是我的代碼的簡短示例:
...
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/abc/:letter', {templateUrl: template, controller: FilterCtrl}).
otherwise({redirectTo: '/abc/a'});
}])
...
控制器:
function FilterCtrl($scope, $http, $routeParams) {
$scope.mainfilter = $routeParams.letter;
$scope.listItems = $http.post($scope.url, {'filterType': 'abc', 'letter': $routeParams.letter});
$scope.searchTitle = function(search) {
$scope.mainfilter = 'Film: ';
//just test code to see if the data changes, will be other http call actually
$scope.listItems = $http.post($scope.url, {'filterType': 'abc', 'letter': 'n'});
}
}
主標記(定義視圖的位置)(Symfony2,忽略樹枝邏輯pls):
...
<div class="sort cell-1022 transparent-gray-back overflow-fix">
<span class="sort--title">Search by</span>
<select class="sort--selected chzn-select" ng-model="searchtitle" ng-change="searchTitle(searchtitle)">
<option value="">film title</option>
{% for id,title in titles %}
<option value="{{ id }}">{{ title }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="divider transparent"></div>
<article class="wrapper">
<div class="transparent-gray-back" ng-view>
</div>
</article>
模板的關鍵部分:
<div class="scroll-list nice-scrollbars" >
<span class="heading">{{ mainfilter.toUpperCase() }}</span>
<ul class="item-list">
<li ng-repeat="item in listItems.data | orderBy:order | filter:filter">
<a ng-click="getRelated(item._id)">{{ item.title }}</a>
</li>
</ul>
</div>
主要問題是,當我在其中有控制器的前兩行時,根據路由參數正確初始化了數據,但是在執行searchTitle()
之后不會更新數據。 當我刪除前兩mainfilter
,不會拉出路由定義的數據(顯然),但是searchTitle()
方法正確地填充了mainfilter
字段和重復的<li>
。 我很拼命,我建議范圍有問題,但是目前我的信息太多了,非常感謝您的幫助,所以!
將控制器的初始“狀態” /默認值包裝為一個函數,並在$viewContentLoaded
事件幫助下調用它。 這是我的解決方法:
$scope.$on('$viewContentLoaded', $scope.init);
$scope.init = function() {
$scope.mainfilter = $routeParams.letter;
$scope.listItems = $http.post($scope.url, {'filterType': 'abc', 'letter': $routeParams.letter});
}
我仍然不知道為什么如果僅通過在控制器代碼中直接分配值來設置默認數據會導致視圖“卡住”該數據,那么我願意重新接受一個更好的答案,解釋這個伏都教。
您可以嘗試以下嗎?
更改您使用$ http.post的方式(在兩個地方)。 嘗試像這樣使用它:
$http.post($scope.url, {'filterType': 'abc', 'letter': $routeParams.letter}).success(function(data) {
$scope.listItems = data;
});
這意味着您的ng-repeat會略有變化:
ng-repeat="item in listItems"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.