In AngularJS, you can get the data source from $rootScope, or you can encapsulate the logic of getting data in a service, then inject it into a function, or inject it into a controller. This article will organize several ways to obtain data.
■ The data source is placed in $rootScope
var app = ("app",[]); (function($rootScope){ $ = [ {item:"",done:true}, {item:"",done:false} ]; }) <div ng-repeat="todo in todos"> {{}} </div> <form> <input type="text" ng-model="newTodo" /> <input type="submit" ng-click=""({item:newTodo, done:false}) /> </form>
As a result, putting the data source in a field in $rootScope is easy to be rewritten.
■ Place the data source in the service and inject the service into the run function
("TodoService", function(){ = [ {item:"",done:true}, {item:"",done:false} ]; }) (function($rootScope, TodoService){ $ = TodoService; }) <div ng-repeat="todo in "> {{}} </div> <form> <input type="text" ng-model="newTodo" /> <input type="submit" ng-click=""({item:newTodo, done:false}) /> </form>
It seems that this is better to write in html:
<input type="submit" ng-click=""(newTodo) />
Add a method to the service:
("TodoService", function(){ = [ {item:"",done:true}, {item:"",done:false} ]; = fucntion(newTodo){ ({item:newTodo, done:false}) } })
■ Place the data source in the service and inject the service into the controller
("TodoCtrl", function($scope, TodoService){ = TodoServce; })
In the corresponding html:
<body ng-app="app" ng-controller="TodoCtrl as todoCtrl"> <div ng-repeat="todo in "> {{}} </div> </body> <form> <input type="text" ng-model="newTodo" /> <input type="submit" ng-click="(newTodo)"/> </form>
■ Place the data source in the service, inject the service into the controller, and interact with the server.
In actual projects, the service also needs to interact with the server.
var app = ("app",[]); ("TodoService", function($q, $timeout){ = function(){ var d = $(); //Simulate a request $timeout(function(){ ([ {item:"", done:false}, ... ]) },3000); return ; } = function(item){ ({item:item, done:false}); } }) ("TodoCtrl", function(TodoService){ var todoCtrl = this; ().then(function(result){ = result; }) = ; })
The above is the method of obtaining data sources in AngularJS. I hope it will be helpful to everyone's learning.