【发布时间】:2016-06-24 05:58:18
【问题描述】:
在我的项目中,用户可以从外部 api 搜索抽认卡集的类别。返回信息时,每组的名称会使用 ng-repeat 显示。我还在 ng-repeat 中附加了一个 ng-click 函数,它复制集合 id,然后发送另一个 $http get 请求,该请求返回有关该特定集合的信息。
这里是html:
<form ng-submit='getCategories(searchTerm)'>
<input ng-model='searchTerm' placeholder="Search Categories">
</form>
<ul>
<li ng-repeat='name in categories' ng-click='getCategory(name.id)' ui-sref='category'>{{name.category}}</li>
</ul>
我的问题是,当用户单击一个集合时,视图会通过 ui-sref 更改,该函数会触发 $http 请求,我可以通过控制台记录信息,但它不会显示在新视图上。我知道每次状态更改时控制器都会“刷新”,但我不知道如何克服这个问题。
这里是控制器:
angular.module('FlashCards').controller('categoryCtrl', function($scope, flashcard){
$scope.getCategory = function(setId){
flashcard.getCategoryById(setId)
.then(function(response){
$scope.category = response;
})
}
});
这里是服务:
angular.module('FlashCards').service('flashcard', function($http, $q){
this.getCategoriesBySearch = function(searchTerm){
var deferred = $q.defer();
$http({
method: "GET",
url: "https://www.coursehero.com/api/flashcards/categories/?api_key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&starts_with=" + searchTerm
}).then(function(response){
deferred.resolve(response.data.data);
})
return deferred.promise;
};
this.getCategoryById = function(setId){
var deferred = $q.defer();
$http({
method: "GET",
url: "https://www.coursehero.com/api/flashcards/categories/" + setId + "/sets/?api_key=YMBXVufy7GkBKoVE34SAMAZJfPVapK32"
}).then(function(response){
deferred.resolve(response.data.data);
})
return deferred.promise;
};
});
如果问题的任何部分需要更多解释,请告诉我。谢谢。
【问题讨论】:
-
使用定义的状态上的 resolve 属性在状态变化时向控制器提供数据
-
在 StateProvider 配置文件中使用 'resolve' 属性。查看this(https://github.com/angular-ui/ui-router/wiki) 链接寻求帮助。
-
你能附上一个plunkr吗?
标签: javascript angularjs