javascript - AngularJS : Use factory inside a controller

标签 javascript angularjs angularjs-service angularjs-controller

我使用 angularjs 种子并尝试编写一个简单的工厂并将其插入到 Controller 中。

我有一个 Row 工厂定义

angular.module('myApp')
.factory('Row', [ function () {
 return 'some string';
 ); 
}])

在我的 view1 Controller 中我有

'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) {
}]);

我收到一个错误,它没有找到 Row 工厂。

最佳答案

您的工厂应该使用 myApp.view1 模块,因为 myApp 模块未定义。

angular.module('myApp.view1')
.factory('Row', [function() {
    return 'some string';
}])

更新

如果您想创建一个新模块并向其附加工厂,那么您应该创建一个新模块并将先前的依赖项包含在 [] 数组中。

angular.module('myApp', ['myApp.view1'])
.factory('Row', [function() {
    return 'some string';
}])

注意:此 JS 应该在工厂 JS 之后加载,以使 myApp.view1 可用。

<小时/>

看起来您只从工厂返回字符串值。我想说,您可以制作constant/value,而不是拥有工厂。其中,使 constant 成为首选方式。因为它也将在配置阶段可用。

angular.module('myApp.view1')
.constant('Row', 'some string');

关于javascript - AngularJS : Use factory inside a controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31004210/

相关文章:

c# - 经过身份验证的调用

javascript - 如何将下面的代码编写为 jquery?

javascript - 如何修改表单操作添加选定的单选按钮值

javascript - 如何使用 ag 网格中列的值创建数组?

angularjs - For 循环和 Promise

javascript - 使用 Javascript 的 ISO 持续时间

javascript - 是否有公认的 Angular 2 生态系统?

css - angularjs 绑定(bind) nbsp 实体在 IE 中不起作用

javascript - 使用多个服务的 Angular.js Controller

将 Controller 函数绑定(bind)到 DOM 时,Firefox 发送多个 XHR 请求