我正在构建一个演示应用。我希望这个AngularJS应用程序也有工厂。
我一直收到错误:“SyntaxError:function statement需要名称”
以下是我的代码:
var bookApp = angular.module('bookAppModule',[]);
bookApp.controller('boookbAppCtrl', ['$scope','$http',Book ,
function($scope,$http,Book) {
$scope.way=["Normal","$http","RestFul"];
$scope.books =
[
{"title":"abc","author":"zxc"},
{"title":"def","author":"cvb"},
{"title":"ghi","author":"nml"},
{"title":"jkl","author":"kjh"},
{"title":"mno","author":"fds"}
];
var names=["Anuj","Donvir"];
$scope.newbooks = Book.getBooks;
}]);
bookApp.factory('Book',
function(){
getBooks : function(){
return
[
{"title":"newbook1","author":"zxc"},
{"title":"newbook2","author":"cvb"},
{"title":"newbook3","author":"nml"},
{"title":"newbook4","author":"kjh"},
{"title":"newbook5","author":"fds"}
];
}
});
答案 0 :(得分:3)
在您的工厂中,您忘记编写返回所有'方法的整体返回功能。在服务中。
bookApp.factory('Book',
function(){
return { // you did not have this return, only its body
getBooks : function(){
return
[
{"title":"newbook1","author":"zxc"},
{"title":"newbook2","author":"cvb"},
{"title":"newbook3","author":"nml"},
{"title":"newbook4","author":"kjh"},
{"title":"newbook5","author":"fds"}
];
}
}
});
<强>加成强>
另外,为了补充导致错误的上述原因,我个人与角度服务中的类似错误进行了多日斗争。这是因为整体return
函数与{
的{{1}}不在同一行,而return
包含// will cause the error
bookApp.factory('Book',
function(){
return
{ // { below not on same line with return
getBooks : function(){
// ...
}
}
});
// will not cause the error
bookApp.factory('Book',
function(){
return { // { on same line with return
getBooks : function(){
// ...
}
}
});
的正文。见下文。
{{1}}
我不知道这种行为的确切原因,但我所知道的是,当你在同一行使用它们时,它会起作用,你不必像我多次那样拖延你的项目。
答案 1 :(得分:0)
如果您需要忘记大括号的位置,可以使用Revealing Module Pattern定义此角度工厂,如下所示...
bookApp.factory('Book',
function(){
var factoryServices=
{
getBooks: getBooks
};
return factoryServices;
function getBooks()
{
// ...
}
}
});
更多阅读:https://github.com/johnpapa/angular-styleguide#style-y052