The initial setup:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { message: "I'm data from a service" }
});
function FirstCtrl($scope, Data) {
$scope.data = Data;
}
function SecondCtrl($scope, Data) {
$scope.data = Data;
}
We’ll add a function reversedMessage() to the SecondCtrl $scope as follows:
function SecondCtrl($scope, Data) {
$scope.data = Data;
$scope.reversedMessage = function() {
return $scope.data.message.split("").reverse().join("");
};
}
Now, as with variables in the scope, the reversedMessage() method can now be invoked in the view:
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.message">
<h1>{{ reversedMessage() }}</h1>
</div>
Instead of referencing the data.message model within the method definition, it is better to pass in the data as a parameter to the reversedMessage() method. This removes the scope dependency inside the method which is cleaner and allows for easier testing.
The data.message model is passed to the invoked method as a parameter:
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data.message">
<h1>{{ reversedMessage(data.message) }}</h1>
</div>
And it is used in the method simply as the message parameter:
function SecondCtrl($scope, Data) {
$scope.data = Data;
$scope.reversedMessage = function(message) {
return message.split("").reverse().join("");
};
}