Let us say that I have the following controller with the following service:
angular.module('ionicApp').controller("MyCtrl", function($scope, MyService){
$scope.MyVariable = MyService.getMyVariable();
$scope.updateMyVariable = function(valueFromHTML){
MyService.setMyVariable(valueFromHTML);
$scope.MyVariable = MyService.getMyVariable();
};
})
.service("MyService", function(){
this.MyVariable = {};
this.getMyVariable = function(){
return this.MyVariable;
}
this.setMyVariable = function(value){
this.MyVariable = value;
return true;
}
});
Now let us take the following HTML:
<div class="instance-1" ng-controller="MyCtrl">
<div class="info-from-controller">
<p>{{MyVariable}}</p>
</div>
</div>
<div class="instance-2" ng-controller="MyCtrl">
<button ng-click="updateMyVariable('newValue')">Click me</button>
</div>
And let us say that it is not possible to put the 2 html parts in the same div, it has to be a different instance of the controller.
If I press the button, thus changing the content of the variable in the service, will it also change the value of the variable in both scopes, since it's calling the service ?
I would naturally say "only in the scope being in the same instance as the button updating the variable". My impression is confirmed by this jsFiddle.
But then, how should I proceed to update the second scope as well? Is there a way to "trigger" the controller so it checks the content of the service again?
The ideal solution, in my case, would be to be able to call the content of the service from the HTML. However, I don't know how to do it, after having tried many things.
Any help would be much appreciated, thank you guys!
When you call updateMyVariable
, it updates $scope.MyVariable
only in the 2nd instance. You're right, you should call the content of the service from the template.
Fiddle: http://jsfiddle.net/5rsr2grg/1/
Calling functions directly from the template can greatly reduce the performance of the application. It is worth doing this only when the called function does not perform complex actions. For example, when it only gets some variables/properties/etc. But in your case everything is ok.