Search code examples
javascriptangularjsangularjs-service

Angular services giving "TypeError: Cannot read property 'helloConsole' of undefined"


I'm studying AngularJS Services and I'm having a problem.

That's my Angular code:

var app = angular.module("todoListApp");

app.controller('MainController', MainController);

MainController.$inject = ['$scope'];

function MainController($scope, dataService){ 
    $scope.helloConsole = dataService.helloConsole;
};

app.service('dataService', function(){
    this.helloConsole = function(){
        console.log("console services");
    };
});
That's my HTML Code

<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
        <div class="actions">
            <a href="" ng-click=" editing = !editing">Edit</a>
            <a href="" ng-click="helloConsole()">Save</a>
            <a href="" class="delete">Delete</a>
        </div>
</div> 
</div>

I'm trying to make it so that when I click on Save, the console shows me "console services", but it's giving me an error:

angular.js:13424 TypeError: Cannot read property 'helloConsole' of undefined


Solution

  • Proper Angular Structure

    you need to change the way you have written your code. It should look more like this

    angular.module("todoListApp", [])
    
    .controller('MainController', ['$scope', 'dataService', function($scope, dataService){
    
        $scope.helloConsole = dataService.helloConsole;
    
    }])
    
    .service('dataService', [function(){
        this.helloConsole = function(){
            console.log("console services");
        };
    }]);
    

    Also this is a 'data service' is this gettig data with a http call? Because if so then make a factory.

    • Controllers for business logic
    • Factories for data requests
    • Services for things like login
    • Directives for DOM manipulation
    • Filters for format