Controller:-The controller directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.
MVC components in angular:
- Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties are accessed through bindings.
- View — The template (HTML with data bindings) that is rendered into the View.
- Controller — The controller directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values
Example:-
<script> function studentController($scope) { $scope.name= { firstName: "Unified", lastName: "Solution", fullName: function() { var name; name = $scope.name; return name.firstName + " " + name.lastName; } }; } </script>
Now we bind the value of controller in view using expressions and ng-model,
First name: <input type = "text" ng-model = "name.firstName"><br> Last name: <input type = "text" ng-model = "name.lastName"><br> <br> Full Name: {{name.fullName()}}
Output look like this,
First name:Last name: Full Name: Unified Solution
Services:-
AngularJS services are substitutable objects that are wired together using dependency injection. You can use services to organize and share code across your app.
AngularJS services are:
- Lazily instantiated – AngularJS only instantiates a service when an application component depends on it.
- Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
There are three ways to create services:-
1:- Using module.factory()
.factory('User' , ['$http',function($http) { var service= { user: {}, login: function(email, pwrd) {, $http.get('/auth', {username: email, password: pwd}) .success(function(data){
}); }; register: function(newuser) { return $http.post('/users', newuser); } }; return service; }]);
2:- Using module.service()
.service('User' , ['$http',function($http) { var service= this; this.user: {}, login: function(email, pwrd) {, $http.get('/auth', {username: email, password: pwd}) .success(function(data){
}); }; this.register = function(newuser) { return $http.post('/user', newuser); };
3:- Using module.provider()
.provider('User', function() { return { this.$get = function($http) { var service = this; this.user = {}; this.login = function(email, pwd) { $http.get('/auth', {username: email, password: pwd}) .success(function(data) {
}); }; this.register = function(newuser) { return $http.post('/users', newuser); }; }}});
0 Comments