三种AngularJS中获取数据源的方式

前端技术 2023/09/07 JavaScript

在AngularJS中,可以从$rootScope中获取数据源,也可以把获取数据的逻辑封装在service中,然后注入到app.run函数中,或者注入到controller中。本篇就来整理获取数据的几种方式。

■ 数据源放在$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 type=\"submit\" ng-click=\"\"todos.push({item:newTodo, done:false}) />
</form>

以上,把数据源放在$rootScope中的某个字段中,很容易被重写。

■ 数据源放在service中,把servie注入到run函数中

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>

在html中似乎这样写比较好:

<input type=\"submit\" ng-click=\"\"TodoService.todos.addodo(newTodo) />

在service中增加一个方法:

app.service(\"TodoService\", function(){
  this.todos = [
    {item:\"\",done:true},
    {item:\"\",done:false}
  ];
  
  this.addTodo = fucntion(newTodo){
    this.todos.push({item:newTodo, done:false})
  }
   
})

■ 数据源放在service中,把servie注入到controller中

app.controller(\"TodoCtrl\", function($scope, TodoService){
  this.TodoService = TodoServce;
})
 

在对应的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>

■ 数据源放在service中,把servie注入到controller中,与服务端交互

在实际项目中,service还需要和服务端交互。

var app = angular.module(\"app\",[]);

app.service(\"TodoService\", function($q, $timeout){
  this.getTodos = function(){
    var d = $q.defer();
    
    //模拟一个请求
    $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;
})

以上就是AngularJS中获取数据源的方法,希望对大家的学习有所帮助。

本文地址:https://www.stayed.cn/item/19849

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。