In my previous article, I described the AngularJs scope. You can read it from the following link.
AngularJS - Scopes: Part 3
Data Binding in AngularJS
Remember that one example I mentioned at the end of my first article, AngularJS, an Introduction?
That can actually be one of the most basic examples of data binding in AngularJS.
I'll re-state it in case you do not remember. It was
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
Here, as we have a model bound to the "username" property, the <h1> element is updated along with the text that is typed into the TextBox. So we can say that the data of the input element is bound to an application model and that causes the DOM to update as soon as the application model is updated. In this way, we can manipulate the DOM using data binding in an interesting way.
Controllers in AngularJS
Now that we have talked about data binding, the next big thing is the controller. For this, we'll take the data from the model and extract it out to the controller that will provide data for this view from now on.
<div ng-controller="firstCtrl">
<h1>Hello {{yourName}}!</h1>
</div>
<script>
function firstCtrl($scope) {
$scope.yourName = "Shashank";
}
</script>
The code inside the element with the "ng-controller" attribute will have the same scope as the controller "firstCtrl". The property of scope "yourName" is now backed by the JS controller method we defined. This is how we are going to push data from any service or file into the view rather than asking the user for it as in the first case.
Now that we have already discussed the scopes and their data sharing in the earlier article, AngularJS - Scopes, a case that arises is, sharing data between two controllers.
As discussed in scopes, instead of creating a parent scope for the two controllers, I'll just get a little help from the service to get you its basic idea. We shall discuss it in detail later.
I will create a small service that will work as a data provider for both controllers.
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return "Shashank";
});
function oneCtrl($scope, Data) {
$scope.username = Data;
}
function twoCtrl($scope, Data) {
$scope.username = Data;
}
<div ng-app="myApp">
<div ng-controller="oneCtrl">
{{ username }}
</div>
<div ng-controller="twoCtrl">
{{ username }}
</div>
</div>
Since we have created a service in the factory, we can inject it into the two controllers as a dependency. This way, we can simply assign the data returned by the service to the scope properties. Thus this data can be shared and modified by both of the controllers.