如何使用angular js 1将数据从一个控制器传递到另一个控制器 [英] how to passing data from one controller to another controller using angular js 1

查看:170
本文介绍了如何使用angular js 1将数据从一个控制器传递到另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我使用angular js的人,我都需要将值从一个页面控制器转移到另一个页面控制器,并将该值放入一个作用域中,任何人都可以帮助实现此目的

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this

var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
 function ($scope, $http, $window, $filter, $notify, $cookieStore)
 {
   $scope.Message="Hi welcome"

 }]);

现在我想将作用域消息显示到page2控制器中

 var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
    app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
     function ($scope, $http, $window, $filter, $notify, $cookieStore)
     {
       ///here i want get that scope value

     }]);

推荐答案

使用服务将数据从一个控制器共享到另一个控制器

我们可以创建一个服务来在controllers之间的setget数据,然后将该服务注入到要使用它的控制器功能中.

We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.

服务:

app.service('setGetData', function() {
  var data = '';
    getData: function() { return data; },
    setData: function(requestData) { data = requestData; }
});

控制器:

app.controller('Controller1',['setGetData',function(setGetData){

app.controller('Controller1', ['setGetData',function(setGetData) {

//从一个控制器设置数据 $ scope.Message =欢迎光临";
setGetData.setData($ scope.Message);

// To set the data from the one controller $scope.Message="Hi welcome";
setGetData.setData($scope.Message);

}]);

app.controller('Controller2', ['setGetData',function(setGetData) {

  // To get the data from the another controller  
  var res = setGetData.getData();
  console.log(res); // Hi welcome

}]);

在这里,我们可以看到Controller1用于设置数据,而Controller2用于获取数据.因此,我们可以像这样将数据从一个控制器共享到另一个控制器.

Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

这篇关于如何使用angular js 1将数据从一个控制器传递到另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆