Angular does not inject factory into controller

I am trying to inject a factory into my controller.

var app = angular.module('BlogApp', ['ngMaterial']);

app.factory("Post", function ($resource) {
    return $resource("/rest/admin/search/posts");
});

app.controller('postController', ['$scope', function ($scope, Post) {
    $scope.getPost = Post.get({id: 1}, function (data) {
        //do something
    });
}
]);

      

Always get the same error as Post - undefined and "Unable to read property 'get' of undefined" . What am I doing wrong? Thanks in advance!

+3


source to share


3 answers


You missed a parameter required to minify your code:

app.controller('postController', ['$scope', function ($scope, Post) {
    $scope.getPost = Post.get({id: 1}, function (data) {
        //do something
    });
}

      



becomes:

app.controller('postController', ['$scope', 'Post', function ($scope, Post) {
    $scope.getPost = Post.get({id: 1}, function (data) {
        //do something
    });
}

      

+5


source


You don't include Post

dependencies in your list. Just add it:



app.controller('postController', ['$scope', 'Post', function ($scope, Post) { /* ... */ }]);

      

+2


source


Insert your ngResource dependency into your module:

var app = angular.module('BlogApp', ['ngMaterial', 'ngResource']);

      


And add a message factory to your controller :

app.controller('postController', ['$scope', 'Post' function ($scope, Post) {

    $scope.getPost = Post.get({id: 1}, function (data) {
        //do something
    });

}]);

      


Hope it helps.

+1


source







All Articles