In Angularjs, you can get the data source from the $rootscope, or you can encapsulate the logic that gets the data in the service, inject it into the app.run function, or inject it into the controller. This article is to organize the acquisition of data in several ways.
The data source is placed in the $rootscope
var app = Angular.module ("app", []); App.run (function($rootScope) { = [ {item:"", Done:true}, {Item:"", Done:false} ];}) <div ng-repeat= "Todo in Todos" > {{Todo.item}}</div><form> <input type= " Text "ng-model=" Newtodo "/> <input type=" Submit "ng-click=" "Todos.push ({item:newtodo, done:false })/></form>
Above, it is easy to rewrite the data source in a field in $rootscope.
The data source is placed in the service and the Servie is injected into the run function
function () { this. Todos = [ {item:' ", Done:true}, {item:'", Done: false } ]; }) App.run (function($rootScope, Todoservice) { = todoservice;}) <div ng-repeat= "Todo in Todoservice.todos" > {{Todo.item}}</div><form> < Input type= "text" ng-model= "Newtodo"/> <input type= "Submit" ng-click= "" TodoService.todos.push ({item: Newtodo, Done:false})/></form>
In HTML it seems better to write this:
<input type= "Submit" ng-click= "" TodoService.todos.addodo (Newtodo)/>
Add a method to the service:
function () { this. Todos = [ {item:' ", Done:true}, {item:'", Done: false } ]; this. Addtodo = fucntion (newtodo) { the. Todos.push ({Item:newtodo, done: False}) } )
The data source is placed in the service and the Servie is injected into the controller
function ($scope, Todoservice) { this. Todoservice = Todoservce;})
In the corresponding HTML:
<body ng-app= "App" ng-controller= "Todoctrl as Todoctrl" > <div ng-repeat= "Todo in TodoCtrl.TodoService.todos "> {todo.item}} </div></body><form> < Input type= "text" ng-model= "Newtodo"/> <input type= "Submit" ng-click= "TodoCtrl.TodoService.addTodo" ( Newtodo) "/></form>
The data source is placed in the service, and the Servie is injected into the controller, interacting with the server
In a real project, the service also needs to interact with the server.
varApp = Angular.module ("app", []); App.service ("Todoservice",function($q, $timeout) { This. Gettodos =function(){ varD =$q. Defer (); //simulate a request$timeout (function() {d.resolve ([{item:"", Done:false}, ... ]) },3000); returnd.promise; } This. Addtodo =function(item) { This. Todos.push ({item:item, done:false}); }}) App.controller ("Todoctrl",function(todoservice) {varTodoctrl = This; Todoservice.gettodos (). Then (function(Result) {Todoctrl.todos=result; }) Todoctrl.addtodo=Todoservice.addtodo;})
Several ways to get data sources in Angularjs