我可以在另一个控制器中获取一个控制器的角度变量(按 $http 变量)

Can I get Angular variable of one controller in other (variable by $http)

本文关键字:控制器 变量 http 另一个 获取 我可以 一个      更新时间:2023-09-26

我是Angularjs的新手,学习了很多。但我坚持了一点。谷歌没有帮助我。我有一个控制器,我有数据$scope.results

app.controller('manage_categories', function($scope, $http, $filter, $window) {
     $scope.results = [];
     $http({
        url: base_url + 'employee/fetchData?table=results',
        method: "POST",
    }).success(function(data) {
        $scope.results = data;
    }); 
})

现在我想在其他中访问相同的内容,而无需任何其他$http调用。我已经完成了另一个电话,但我不想要这个.因为我在许多其他控制器中都需要这个。像这样

app.controller('manage_users', function($scope, $http, $filter, $window,results) {
     $scope.results = results;
     //~ $http({
        //~ url: base_url + 'employee/fetchData?table=results',
        //~ method: "POST",
    //~ }).success(function(data) {
        //~ $scope.results = data;
    //~ });
})

或任何其他方法。谢谢。

更新

我试过这个

var myApp = angular.module('myApp',[]);
myApp.factory('results', function() {
  return {
      name : [{id:21,name:'this is test'}]
  };
});
app.controller('manage_users', function($scope, $http, $filter, $window,results) {
         $scope.results = results;
    })

这工作正常.但不与$http通话一起工作.

var myApp = angular.module('myApp',[]);
    myApp.factory('results', function($scope,$http) {
       $scope.results=[];
       $http({
            url: base_url + 'employee/fetchData?table=results',
            method: "POST",
        }).success(function(data) {
            $scope.results = data;
        }); 
      return {
          name : results
      };
    });

更新 2

回答后我写成

var canapp = angular.module('canApp', ["ngRoute", "angularFileUpload"]);
canapp.service('ResultsFactory', ['$http', function($http) {
   // http call here
   var url=base_url + 'employee/fetchData?table=results';
   $http.post(url,data).success(function(data){
               this.results = data;
          });
}])

像这样打电话

canapp.controller('get_candidates', function($scope, $http, $filter, $timeout, $window, ResultsFactory) {
$scope.check=ResultsFactory.results;
});

但它没有在模板中设置值

使用 $broadcast 在控制器之间共享数据。您的代码将如下所示

app.controller('manage_categories', function($scope, $http, $filter, $window, $rootScope) {
     $scope.results = [];
     $http({
        url: base_url + 'employee/fetchData?table=results',
        method: "POST",
    }).success(function(data) {
        $scope.results = data;
        $rootScope.$broadcast("results",data);
    }); 
});
app.controller('otherCtrlr', function($scope, $rootScope) {
         $rootScope.$on("results", function(event, data){
            $scope.results = data;
         });
    });

但是,在控制器中使用服务调用并不是最佳方法。创建工厂并创建调用服务的方法。 从控制器中,您需要调用此方法。但是为了避免两个服务调用,你肯定需要使用广播/发射(取决于数据传输是来自父级还是子级)

两个控制器之间有多种可能的通信方式。如果你只是谷歌在控制器angularjs之间共享数据,你可能会找到各种链接:

  1. 使用服务在控制器之间共享数据
  2. 在控制器之间共享数据
  3. 在 AngularJS 控制器之间共享数据
  4. 在 Angular JS 中的控制器之间传递数据?

因此,简而言之,可能的方式是:

  1. 使用角度工厂(推荐)
  2. 使用$rootScope(不推荐)
  3. 使用最顶层控制器的作用域作为根作用域

你可以这样做:

app.factory('ResultsFactory', resultsFactory);
resultsFactory.$inject = ['$http'];
function resultsFactory = function(){
   var self = {};
   var results = null;
   self.getResults = function(){
       if(!results){
          $http.post(url,data).success(function(data){
              results = data;
          });
       }else{
          return results;
       }
   }
   return self;
}

只有在第一次调用 ResultsFactory.getResults() 时,才会执行$http调用。

这里有一个小提琴,解释了如何在控制器之间共享数据。

https://jsfiddle.net/frishi/zxnLwz6d/10/

(检查浏览器控制台以查看两个控制器是否都可以通过服务访问数据。

基本上,服务的前提是它是一个单例,可供模块上注册的所有控制器使用。

您希望在服务中进行该$http调用:

.service('myService', ['$http', function($http) {
 this.getData = function(){
    // Simple GET request example:
    return $http({
      method: 'GET',
      url: 'https://api.github.com/users/mralexgray/repos' // example API
    }).then(function successCallback(response) {
        return response;
    }, function errorCallback(response) {
       // return error message
    });
    }
 }])

在控制器中:

.controller('Controller2',['$scope','myService',function ($scope,myService) {
   $scope.foo = myService.getData();
   //resolve the promise:
   $scope.foo.then(function(data){
     console.log(data);
   })
 }
])

强烈建议使用单独的服务,正如 frishi 指出的那样。此示例位于单个文件和模块中,只是为了使其可读。以下实现存储承诺和实际请求仅在对getFoo的初始调用时提出。其余的将从内存中承诺获得响应。

'use strict';
angular.module('foo', [])
.factory('FooResource', function SessionResource($http) {
    var fooPromise;
    return {
      getFoo: function getFoo() {
        if(!fooPromise) {
          fooPromise = $http.post('employee/fetchData?table=results');
        }
        return fooPromise;
      }
    };
})
.controller('FooController', function($scope, FooResource) {
  FooResource.getFoo().then(function getFooSuccess(data) {
    $scope.results = data;
  });
});

我将这个角度代码与离子框架一起使用也许它可以帮助你..

我的工厂是..

angular.module('starter.services', [])
    .factory('Chats', function() {
      // Might use a resource here that returns a JSON array
      // Some fake testing data
      var chats = [{
        id: 0,
        name: 'Ben Sparrow',
        lastText: 'You on your way?',
        face: 'img/ben.png'
      }, {
        id: 1,
        name: 'Max Lynx',
        lastText: 'Hey, it''s me',
        face: 'img/max.png'
      }, {
        id: 2,
        name: 'Adam Bradleyson',
        lastText: 'I should buy a boat',
        face: 'img/adam.jpg'
      }, {
        id: 3,
        name: 'Perry Governor',
        lastText: 'Look at my mukluks!',
        face: 'img/perry.png'
      }, {
        id: 4,
        name: 'Mike Harrington',
        lastText: 'This is wicked good ice cream.',
        face: 'img/mike.png'
      }];
      return {
        all: function() {
          return chats;
        },
        remove: function(chat) {
          chats.splice(chats.indexOf(chat), 1);
        },
        get: function(chatId) {
          for (var i = 0; i < chats.length; i++) {
            if (chats[i].id === parseInt(chatId)) {
              return chats[i];
            }
          }
          return null;
        }
      };
    });

我在许多控制器中都使用这个工厂

.controller('ChatsCtrl', function($scope, Chats) {
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

在此代码工厂中 http://仅命中一次请求,我在两个控制器上使用响应。希望对您有所帮助。