Reputation: 1
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
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