[英]AngularJS : Use factory inside a controller
I use angularjs seed and trying to write a simple factory and insert it in to the controller. 我使用angularjs种子,尝试编写一个简单的工厂并将其插入到控制器中。
I have a Row factory definition 我有一个行工厂定义
angular.module('myApp')
.factory('Row', [ function () {
return 'some string';
);
}])
inside my view1 controller I have 在我的view1控制器中
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', 'Row', function($scope, Row) {
}]);
And I am getting an error it's not finding the Row factory. 我收到一个错误,找不到行工厂。
Your factory should be using myApp.view1
module as myApp
module is not defined. 您的工厂应该使用
myApp.view1
模块,因为未定义myApp
模块。
angular.module('myApp.view1')
.factory('Row', [function() {
return 'some string';
}])
Update 更新资料
If you wanted to create a new module and append factory to it, then you should create a new module and include the previous dependency inside the []
array. 如果要创建一个新模块并向其追加工厂,则应创建一个新模块,并在
[]
数组中包含以前的依赖项。
angular.module('myApp', ['myApp.view1'])
.factory('Row', [function() {
return 'some string';
}])
Note: this JS should be loaded after the factory JS in order to make myApp.view1
available. 注意:此JS应该在工厂JS之后加载,以便使
myApp.view1
可用。
It seems like you are returning only string value form your factory. 似乎您只从工厂返回字符串值。 I'd say rather than having factory, you could make
constant
/ value
. 我要说的是,除了拥有工厂之外,您还可以使
constant
/ value
。 Out of which making constant
would be preferred way of doing it. 从中使
constant
成为首选的方式。 As it will be available in config phase as well. 因为它将在配置阶段也可用。
angular.module('myApp.view1')
.constant('Row', 'some string');
告诉“ myApp.view1”使用“ myApp”。
angular.module('myApp.view1', ['ngRoute', 'myApp'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.