service
The service is only instantiated once, which is actually the idea of the singleton pattern. No matter where we inject our service, the same instance will always be used. Therefore, many operations in the controller layer can be placed in the service layer.
Servies generally use this directly to manipulate data and define functions.
app.service('myService', function() { var privateValue = "I am Private"; this.variable = "This is public"; this.getPrivate = function() { return privateValue; }; });
The service() method is very suitable for use in services with more functional control
<div ng-controller="myCtrl"> <button ng-click="getPrivate()">按钮一</button> <button ng-click="getPUbluc()">按钮二</button> </div> <div ng-controller = "myCtrl2"> </div>
var app = angular.module ('myApp', []); app.controller('myCtrl', function($scope, myService) { $scope.getPrivate = function() { alert(myService.getPrivate()); }; $scope.getPUbluc = function() { alert(myService.variable); }; }); app.controller('myCtrl2', function($scope, myService) { }); app.service('myService', function() { console.log('instance myService'); var privateValue = "I am Private"; this.variable = "This is public"; this.getPrivate = function() { return privateValue; }; }); </script>
Factory
Factory generally creates an object, then adds methods and data to this object, and finally returns some objects. Then inject it into the Controller layer.
var app = angular.module ('myApp', []); app.controller('myCtrl', function($scope, myFactory) { $scope.getPrivate = function() { alert(myFactory.getPrivate()); }; $scope.getPUbluc = function() { alert(myFactory.variable); }; }); app.controller('myCtrl2', function($scope, myFactory) { }); app.factory('myFactory', function() { console.log('instance myFactory'); var factory =}; var privateValue = "I am Private"; factory.variable = "This is public"; factory.getPrivate = function() { return privateValue; }; return factory; }); </script>
directive custom directive
angular.module("app",[]) .directive("directive",function(){ return{ restrict:"EACM", //indicate in what form the directive is declared in the DOM priority:0, //the execution priority of the instruction terminal:true/false, //Whether it is the last set of directives to be executed. template:"<div></div>", //template template:"**/**.html", //Specify the url of the template replace:true/false, //replace or splice to the current element transclude:true/false/'element', // put the content into the specified place after compiling scope:true/false/{}, //create a new scope require:[], //request controller of other directive controller:function/controllerName, //Create a controller that can be shared with other .directives link:function, //Manipulate DOM elements compile:function, //modify the DOM template through the presentation server }; })