AngularJS-如何在ng-click()上将数据从一个控制器传递到另一个控制器? [英] AngularJS- How to pass data from one controller to another on ng-click()?

查看:43
本文介绍了AngularJS-如何在ng-click()上将数据从一个控制器传递到另一个控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图在一个单击事件上在两个控制器之间共享数据.我的代码如下:

So I am trying to share data between two controllers on an on-click event. My code is as follows:

控制器

function userTypeController($scope, $location, CategoryService) {
  let vm=this;

vm.getCat=function(){

    CategoryService.getCategories() .then(function (response) 
        {
          $scope.categories=response.data.data.categories;
          $scope.index = 0;
          $scope.array = [];
          for(var i=0; i<$scope.categories.length/2;i++)
          $scope.array.push(i);


                                       });
    $location.path('/category');
};
  };

用我的html表示该控制器,我有一个调用getCat函数的按钮.

Say in my html for that controller, I have a button that calls the getCat function.

 <md-button md-whiteframe="8"  ng-click="utCtrl.getCat()">Submit<md-button>

在我的类别服务中,我有一个返回类别列表的函数.

In my category service , I have a function that returns a list of categories.

服务

return {
            getCategories: function () {
                return $http.get(url2);
            }

现在,我希望从服务器中获得的类别数组可以在我的类别控制器中访问.我之前使用$ rootScope将用户类型控制器的日期共享给另一个控制器,但这并不是理想的选择.我希望在我的类别控制器中可以访问$ scope.array,以便可以在其视图中显示它.什么是做到这一点的最佳方法.非常感谢!

Now i want the array of categories that I get from the server to be accessible in my Categories controller. I was using $rootScope before to share the date from usertype controller to the other one but its not the ideal thing to do. I want $scope.array to be accessible in my categories controller so i can display that in its view. What would be the best way to do this. Thanks a lot!

推荐答案

在这种情况下,您应该考虑使用服务在控制器之间共享数据.

You should consider using a service in this case to share the data across your controllers.

SharedService.js

app.service('sharedService', function(){
  var categories = [];  
  names.add = function(incategories){
    categories = incategories;
  };
  names.get = function(){
    return categories;
  };     
});

然后注入您的controller1和controller2并根据您的要求进行使用.

then inject in your controller1 and controller2 and use depending on your requirement.

 app.controller("TestCtrl", 
   function($scope,sharedService) {
    $scope.categories =[];
    $scope.save= function(){
      sharedService.add(yourcat);
    }   
   }
  );

然后将其用作

 app.controller("TestCtrl2", 
   function($scope,sharedService) {      
   $scope.getcategories = function(){
     $scope.categories = sharedService.get();
   }
  }
 );

这篇关于AngularJS-如何在ng-click()上将数据从一个控制器传递到另一个控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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