When you Angular, it's natural to heap unnecessary logic in the controller and scope. Be sure to realize early that the controller layer should be thin, that is, most of the business logic and persistent data in the application should be in service. I see a couple of similar questions on Stack Overflow every day about how to save persistent data in a controller. This is not what the controller should do. For memory performance, the controller initializes only when needed, and is discarded once it is not needed. Therefore, each time you switch or refresh the page, Angular will empty the current controller. At the same time, the service can be used to permanently save the app's data, and the data can be used between different controllers.
Angular provides 3 ways to create and register our own service
A:factory,b:service, C:provide
1) using Factory is to create an object (var service), add a property (Service.getlist) to it, and then return the object. After you pass the service into the controller, the properties of this object in the controller can be used by factory.
Myapp.factory ("Indexfactory", function ($http) {var _artist = " var service = {} service.getlist = function ( ) { return _artist;} Service.newlist = function (callback) {$http. JSONP ("http://tingapi.ting.baidu.com/v1/restserver/ting?method= Baidu.ting.billboard.billlist&type=1&size=10&offset=0&callback=json_callback "). Success ( function (Result) { callback (result); return service;})
2) The Service is instantiated with the "new" keyword. Therefore, you should add a property to "this" and then the service returns "this". After you pass the service into the controller, the properties on the "This" in the controller can be used by the service.
Myapp.service (' Indexsever ', function ($http) {var = this; Self.newsjh2=function (callback) { $http. Jsonp ("http://tingapi.ting.baidu.com/v1/restserver/ting?method= Baidu.ting.billboard.billlist&type=1&size=10&offset=0&callback=json_callback "). Success ( function (Result) { callback (Result), }) })
Myapp.controller (' Firstcontroller ', function ($scope, $interval,indexsever,indexfactory) { INDEXSEVER.NEWSJH2 (function (result) {
Console.log (Result) }) indexfactory.newlist (function (result) { console.log (result); } )
The above effect is the same, see oneself like to use that kind, that high efficiency still don't know, have the big God pointing please inform under
AngularJS Services-$provide factory, service methods