我正在使用AngularJS创建我的投资组合。我为我的所有项目创建了一个projects.json文件。我想在单击特定项目按钮时打开模态。所以我创建了一个函数,它将id作为参数,并根据该id找到一个项目。但它给了我未定义的错误。
(function() {
'use strict';
angular.module('myPortfolio')
.controller('ProjectCtrl', function($scope, projectFactory, $state) {
var projectCtrl = this;
projectCtrl.projects;
projectFactory.getProjects().then(function(projects) {
projectCtrl.projects = projects.data;
console.log(projectCtrl.projects);
});
projectCtrl.openProject = openProject();
function openProject(id) {
for (var i = 0; i < projectCtrl.projects.length; i++) {
if (projectCtrl.projects[i].id === id) {
projectCtrl.project = projectCtrl.projects[i];
}
}
console.log(projectCtrl.project);
};
});
})()
(function() {
'use strict';
angular.module('myPortfolio')
.factory('projectFactory', function($http) {
function getProjects() {
return $http.get('components/data/projects.json');
}
return {
getProjects : getProjects
}
});
})();
angular.js:13550 TypeError: Cannot read property 'length' of undefined
at openProject (projects.controller.js:18)
at new <anonymous> (projects.controller.js:15)
at Object.invoke (angular.js:4665)
at R.instance (angular.js:10115)
at n (angular.js:9033)
at g (angular.js:8397)
at g (angular.js:8400)
at angular.js:8277
at angular.js:1751
at n.$eval (angular.js:17229)(anonymous function) @ angular.js:13550(anonymous function) @ angular.js:10225n.$apply @ angular.js:17334(anonymous function) @ angular.js:1749invoke @ angular.js:4665c @ angular.js:1747yc @ angular.js:1767ee @ angular.js:1652(anonymous function) @ angular.js:30863b @ angular.js:3166Qf @ angular.js:3456Pf.d @ angular.js:3444
projects.controller.js:13 [Object, Object, Object, Object, Object, Object, Object, Object]
答案 0 :(得分:0)
projectCtrl.openProject = openProject();
缺少id
参数。此外,错误告诉您projectCtrl.projects;
未定义。一个好的做法是将其projectCtrl.projects = [];
初始化,以便您可以继续解决真正的问题。
答案 1 :(得分:0)
问题是您在projectCtrl.projects
回调填充之前尝试使用then
。
您似乎不想致电openProject()
,而是尝试将参考设置为projectCtrl.openProject
。
你应该这样做:
angular.module('myPortfolio')
.controller('ProjectCtrl', function($scope, projectFactory, $state) {
var projectCtrl = this;
projectFactory.getProjects().then(function(projects) {
projectCtrl.projects = projects.data;
});
projectCtrl.openProject = openProject; // don't add () after function name
function openProject(id) {
for (var i = 0; i < projectCtrl.projects.length; i++) {
if (projectCtrl.projects[i].id === id) {
projectCtrl.project = projectCtrl.projects[i];
break;
}
}
console.log(projectCtrl.project);
};
});