MindTheBit
MindTheBit

Reputation: 1

Expression not working in the view that is set by a service in AngularJS

I'm quite stuck on trying to access the view with an expression that obviously fails to work. I have a Service:

angular.module('myApp', []).service('myService', function($timeout){
    this.sayHello = function(name) {
        $timeout(function(){
            alert('Hi, I am...' +name);
        }, 3000);
    };
});

Controller:

angular.module('myApp.controllers', [])
.controller('MyController', function(myService) {
    myService.sayHello('AngularJS Service');
});

View

<div ng-controller="MyController">{{sayHello}}</div>

In the view I have:

{{sayHello()}}

What am I doing wrong?

Upvotes: 0

Views: 44

Answers (1)

Dan
Dan

Reputation: 63059

The service function is not bound to the controller, so the view doesn't find it. Do this:

angular.module('myApp.controllers', [])
.controller('MyController', function(myService) {
    this.sayHello = myService.sayHello;
});

To bind to this instead of $scope, you need controllerAs syntax in the view as well, like as c1:

<div ng-controller="MyController as c1">
    {{ c1.sayHello() }}
</div>

Function bindings in the view will fire repeatedly though.

Upvotes: 0

Related Questions