In Angularjs, you can get the data source from the $rootscope, or you can encapsulate the logic of obtaining the data in the service, then inject it into the app.run function, or inject it into the controller. In this article, we'll sort out several ways to get the data.
The data source is placed in the $rootscope
var app = Angular.module ("App", []);
App.run (function ($rootScope) {
$rootScope. Todos = [
{item: ", Done:true},
{item:", Done:false}
];
})
<div ng-repeat= "Todo in Todos" >
{{Todo.item}}}
</div>
<form>
<input type= "text" ng-model= "Newtodo"/> <input
"Submit" Ng-click= "" Todos.push ({Item:newtodo, done:false})/>
</form>
Above, putting the data source in a field in $rootscope is easy to rewrite.
The data source is placed in the service, and the Servie is injected into the run function.
App.service ("Todoservice", function () {
This.todos = [
{item: ", Done:true},
{item:", Done:false}
] ;
})
App.run (function ($rootScope, todoservice) {
$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 like this is a good way to write:
<input type= "Submit" ng-click= "" TodoService.todos.addodo (Newtodo)/>
Add a method to the service:
App.service ("Todoservice", function () {
This.todos = [
{item: ", Done:true},
{item:", Done:false}
];
This.addtodo = Fucntion (Newtodo) {
This.todos.push ({item:newtodo, done:false})
}
)
The data source is placed in the service and the Servie is injected into the controller
App.controller ("Todoctrl", 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, injecting the Servie into the controller, interacting with the server
In actual projects, the service also needs to interact with the server.
var app = Angular.module ("App", []);
App.service ("Todoservice", Function ($q, $timeout) {
This.gettodos = function () {
var d = $q. Defer ();
Simulates a request
$timeout (function () {
d.resolve ([
{item: ", Done:false},
...
])
},3000);
return d.promise;
}
This.addtodo = function (item) {
This.todos.push ({item:item, done:false});
}
)
App.controller ("Todoctrl", function (todoservice) {
var Todoctrl = this;
Todoservice.gettodos (). Then (function (Result) {
Todoctrl.todos = result;
})
Todoctrl.addtodo = Todoservice.addtodo;
})
The above is the method that obtains the data source in Angularjs, hope to be helpful to everybody's study.