我的角度应用程序中存在一个问题,即服务,工厂,用于在控制器之间存储数据。在一个视图中,我将对象推送到列表中并且我确定它继续进行,但每当我转到另一个视图(使用新控制器)时,列表都是空的。
services.js
'use strict';
var services = angular.module('services', ['ngResource']);
services.factory('participants', function () {
var participants = {};
participants.list = [];
participants.add = function(name, sirName, email, answer){
participants.list.push({name: name, sirName: sirName, email: email, answer: answer});
};
return participants;
});
controllers.js
'use strict';
var cont = angular.module('controllers', ['services']);
cont.controller('lottery1Ctrl', ['$scope', 'participants', '$location', '$log',
function ($scope, participants, $location) {
$scope.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
$scope.$apply((function(controller){
return function(){
controller.content = fileContent;
$scope.csvToJson(fileContent);
};
})(this));
};
$scope.checkParticipants = function () {
if(participants.list.length == 0){
alert("Wgraj plik CSV")
}
else
$location.path('/lottery/2');
};
$scope.csvToJson = function (text) {
var lines = text.split("\n");
for (var i = 1; i < lines.length; i++) {
var currentLine = lines[i].split(",");
var answer = currentLine[0];
var name = currentLine[1];
var sirName = currentLine[2];
var email = currentLine[3];
participants.add(name, sirName, email, answer);
}
};
}]);
cont.controller('lottery2Ctrl', ['$scope', 'participants', '$log',
function ($scope, $log, participants) {
$scope.getTotalParticipants = function () {
$log.log(participants.list.length);
return participants.list.length;
};
}]);
cont.controller('ListCtrl', ['$scope', 'participants',
function (participants) {
var self = this;
self.participants = participants.list;
}]);
login2.html
<h3>Participants number: {{getTotalParticipants()}}</h3>
<div ng-controller="ListCtrl as list">
<p ng-repeat="participant in participants.list">{{ participant.name }}: {{ participant.sirName }}: {{ participant.email }}: {{ participant.answer }}</p>
</div>
输出只显示:::,每当我尝试获取列表的长度值时,我都会收到错误&#34;无法读取属性&#39;长度&#39;未定义&#34;
提前致谢!
答案 0 :(得分:1)
我没有看到您的参与者列表被传递到$ scope对象的任何地方,您可以在其中将其绑定到您的html或从ng-repeat引用它。虽然我无法对整个程序发表评论,但在我看来,您需要在控制器中进行声明,例如:
$scope.participants = [];
然后你应该将你的参与者添加到该数组中。尝试将其放入您的代码中,看看它是否在您的网页上显示虚拟值,如果是这样,您可能需要调整您的函数,以便在您的控制器中填充数组:
$scope.participants = [{name:'Test1'},{name:'Test2'}];