user3814030
user3814030

Reputation: 1283

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.

Upvotes: 0

Views: 2664

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

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');

Upvotes: 1

Johnny Ha
Johnny Ha

Reputation: 633

Tell "myApp.view1" to use "myApp".

angular.module('myApp.view1', ['ngRoute', 'myApp'])

Upvotes: 0

Related Questions