简体   繁体   中英

AngularJS : Use factory inside a controller

I use angularjs seed and trying to write a simple factory and insert it in to the controller.

I have a Row factory definition

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

inside my view1 controller I have

'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.

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.


It seems like you are returning only string value form your factory. I'd say rather than having factory, you could make constant / value . Out of which making constant would be preferred way of doing it. 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM