AngularJS:具有动态数据的ng-repeat [英] AngularJS: ng-repeat with dynamic data
问题描述
我正在构建一个简单的AngularJS应用,但是我无法解决有关服务,ng-repeat和动态添加数据的问题.
I'm building a simple AngularJS app, but I couldn't solve a problem regarding services, ng-repeat and dynamically added data.
我要做什么
我的页面被分成几个计数器.
在homeController
中,我有一个文本字段和一个按钮.当我按下按钮时,正在对服务器进行API调用,服务器返回JSON,并将数据设置为Storage
服务.在这一部分中,一切正常-服务器按应有的方式返回数据,并将数据设置为服务,并且我在Storage Service中得到console.log('Data set!');
.在第二个控制器(slidesController
)中,我有一个ng-repeat
My page is splitted into few countrollers.
In the homeController
I have a text field and a button. When I press the button I'm doing an API call to the server, the server returns JSON and I'm setting the data to Storage
service. In this part everything is OK - The server returns data as it should and the data is setted to the service and I'm getting console.log('Data set!');
in the Storage service. In the second controller ( slidesController
) I'm having a ng-repeat
<div ng-controller="slidesCtrl">
<div ng-repeat="current in paragraphs"> test </div>
</div>
正如您在下面的代码中所见,paragraphs
绑定到slidesCtrl
中的Storage.data
值
And as you can see in my code below, paragraphs
is binded to Storage.data
value in slidesCtrl
因此,当用户在框中输入内容并按下按钮(homeCtrl)时,服务器应将返回的数据传递给Storage
服务,并使用ng-repeat(slideCtrl)呈现数据.例如,如果我使用[2、3、4、5]在存储服务器中对数据进行硬编码,一切正常(由于ng-repeat,我进行了4次测试),但是如果数据是通过api调用获取的, ng-repeat无法正常工作.
So, when a user enter something in the box and press the button (homeCtrl), the server should pass the returned data to Storage
service and render the data using ng-repeat (slideCtrl). If I hardcode the data in Storage server with [2, 3, 4, 5] for example, everything is ok ( I'm getting test 4 times, because of ng-repeat ), but if the data is taken with api call, ng-repeat isn't working.
代码
App.controller('homeCtrl', function ($scope, $http, Api) {...
$scope.onprocess = function () {
$scope.loading = true;
Api(.....);
}
});
App.controller('slidesCtrl', function ($scope, Storage) {
$scope.paragraphs = Storage.data.paragraphs; // NOT WORKING IF DATA IS DYNAMICALLY ADDED
$scope.paragraphs = Storage.test; // IF DATA IS PREDEFINED EVERYTHING IS FINE
});
App.factory('Api', function ($http, Storage) {
return function (data) {
$http.post('/api', {
url: data.url,
analyze: 0
}).success(function (res) {....
Storage.set(res);....
}).error(function () {....
});
};
});
App.factory('Storage', function () {
var output = {};
var set = function (data) {
output = data;
console.log('Data set!');
};
return {
set: set,
data: output,
test: [1, 2, 3]
};
});
推荐答案
我发现
angular.copy(data, output);
作为解决方案.
您可以查看有关此主题的更多信息 使用服务AngularJS在两个控制器之间共享动态数据
You can see more information on this topic Sharing dynamic data between two controllers with service AngularJS
谢谢大家.
这篇关于AngularJS:具有动态数据的ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!