gpt4 book ai didi

javascript - AngularJS : Use factory inside a controller

转载 作者:行者123 更新时间:2023-12-03 09:46:43 25 4
gpt4 key购买 nike

我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com