此plnkr:https://plnkr.co/edit/BjETLN7rvQ1hNRIm51zG?p=preview将内容绑定到循环中的三个div:<div ng-repeat="id in ids">
src:
{ "content" : "divContent" , "id" : "r1" }
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="FetchCtrl">
<div ng-repeat="id in ids">
<div ng-bind="content" ></div>
</div>
</div>
</body>
</html>
// Example of how to call AngularJS $http service and
// process the returned promise
function FetchCtrl($scope, $http, $q) {
$scope.ids = ["r1", "r2", "r3"];
$scope.ids = $scope.ids.map(function(id){
var getString = 'http-hello1.html?id='+id
return $http.get(getString);
});
$scope.responses = [];
$q.all($scope.ids).then(function (values) {
var counter = 0;
values.map(function(m){
$scope.content = m.data.content;
})
})
}
但是如何将每个get请求的结果绑定到特定的div?
可以添加id:<div id="{{id}}" ng-bind="content" ></div>
,但这意味着我需要维护id,值条目的映射?是否有一种惯用的angularjs方法来实现这一目标?
答案 0 :(得分:0)
angular.module('whateverYourModuleNameIs')
.directive('dynamicRow', ['$http', '$interval', dynamicRowDirectiveFn]);
function dynamicRowDirectiveFn($http, $interval) {
return {
restrict: "EA", // I guess this is your choice how it renders
scope: {
id: '=' // you could grab the id and use it in your request
},
link: function linkFn(scope, element, attrs) {
// Use $interval to repeatedly fetch content
var repeatFetchWhichReturnsAPromise = $interval(fetchNewContent, 60000 * 15) //Executes function every x milliseconds.
// Function that executes every time your interval occurs
function fetchNewContent() {
$http.get('urlYouNeedToFetch'+id).then(
fetchNewContentSucess, fetchNewContentError
);
}
function fetchNewContentSuccess(responseObject){
//This sets your new HTML based on promise success
element = responseObject.data;
}
function fetchNewContentError(responseObject){
//If its a bad request we probably either want to stop repeating
// You can choose to do something else
$interval.cancel(repeatFetchWhichReturnsAPromise);
}
}
}
}
因此,我建议您不要使用$q.all()
,而是根据计时器或特定触发器单独提取内容。 $q.all()
的缺点是,如果其中一个承诺失败,它们都会失败。
在了解指令需要获取的特定URL方面,您必须将该信息提供给要使用的指令。
这是您可以编写的指令的一个非常粗略的示例。好处是您不必担心bind-unsafe-html
或包含ngSanitize
,而只需在element
函数中重置link
的值。
由于我没有从功能/产品角度更好地了解您要完成的任务,我只能根据提供的信息提出建议。