Luis Luis - 1 month ago 4
AngularJS Question

Print result of two different controllers in AngularJS

I'm starting in AngularJS, and I'm trying to create a very simple program, where a user can choose your favorite fruit and the result is shown below.

This choice can be performed in two different ways: through 3 quick buttons or typing a name in the text entry. These two modes have different controllers.

When I'm using the buttons works well, but not with the text editor.

I want to transfer the name written in the text entry for the controller1 and print the result.

My code is:

<html ng-app="myApp">
<head>
<title>Fruits</title>
<script src="https://code.angularjs.org/1.2.19/angular.js"></script>
<script>
var app = angular.module('myApp',[]);


app.service('simpleService', function() {

var _fruit = 'None :(';

var addFruit = function(newObj) {
console.log(newObj);
_fruit = newObj;
}

var getFruit = function(){
return _fruit;
}

return {
addFruit: addFruit,
getFruit: getFruit
};
})



app.controller('controller1',function($scope, simpleService){

$scope.fruit = simpleService.getFruit();

$scope.fruitApple = function(){
$scope.fruit ='Apple';
}

$scope.fruitPear = function(){
$scope.fruit ='Pear';
}

$scope.fruitBanana = function(){
$scope.fruit ='Banana';
}
})

app.controller('controller2', function($scope, simpleService){
$scope.fruit2 = 'Other?';

$scope.fruitEditor = function(f){
if(angular.isString(f)){
$scope.fruit2 = f;
simpleService.addFruit(f);
}
}
});
</script>

</head>

<body>
<div ng-controller="controller1">
<button ng-click="fruitPear()">Pear</button>
<button ng-click="fruitApple()">Apple</button>
<button ng-click="fruitBanana()">Banana</button>
<br/>
<br/>

<div ng-controller="controller2">
Edit:
<input type="text" ng-change="fruitEditor(fruit2)" ng-model="fruit2">
</div>

<h5>Favorite fruit: {{fruit}}</h5>
</div>
</body>
</html>


Regards.

Answer

Because you are setting fruit value on initial load only. If you wanted to keep it sync with whatever you have inside service you should call getFruit method of service on view, so that it will get latest value from service on each digest cycle to ensure it correct.

$scope.getFruit = simpleService.getFruit;

on view

<h5>Favorite fruit: {{getFruit()}}</h5>

Same thing applies to while setting a rule, you shouldn't be adding fruit in scope variable, just put them inside service variable by calling addFruit method.

simpleService.addFruit('Apple');