简体   繁体   English

如何在angularjs中从一个控制器动态获取数据?

[英]How to get data dynamically from one controller to another in angularjs?

.controller('Ctrl1', function($scope, $http) {

  $scope.langChecked = function(){
   $scope.value = $('input[name=lang-check]:checked').val();
    console.log($scope.value);
  };
})

.controller('Ctrl2', function($scope, $http, $state, Scopes) {
    if($scope.value='something'){
         alert('scope passed');
    }
});

i tried using rootscope and passing values between controllers 我尝试使用rootscope并在控制器之间传递值

.run(function ($rootScope) {
    $rootScope.$on('scope.stored', function (event, data) {
        console.log("scope.stored", data);
    });
})
.factory('Scopes', function ($rootScope) {
    var mem = {};

    return {
        store: function (key, value) {
            $rootScope.$emit('scope.stored', key);
            mem[key] = value;
        },
        get: function (key) {
            return mem[key];
        }
    };
});

but my ctrl2 page loads first on refresh and it gives error when i use 但我的ctrl2页面在刷新时首先加载,当我使用时它会出错

Scopes.get('Ctrl1').value;

in Ctrl2. 在Ctrl2中。 Please help 请帮忙

you have to inject your factory with $rootscope . 你必须用$rootscope注入你的工厂。

Factories don't have access to the current controller/directive scope because there isn't one. 工厂无法访问当前的控制器/指令范围,因为没有。 They do have access to the root of the application though and that's why $rootScope is available 他们确实可以访问应用程序的根目录,这就是$ rootScope可用的原因

.factory('Scopes',["$rootScope", function ($rootScope) {
    var mem = {};

    return {
        store: function (key, value) {
            $rootScope.$emit('scope.stored', key);
            mem[key] = value;
        },
        get: function (key) {
            return mem[key];
        }
    };
}]);
.factory('Authorization', function() {
  authorization = {};
  authorization.variable= '';
  return authorization;
})

.controller('Ctrl1', function($scope, Authorization) {
  $scope.input = Authorization;
  console.log($scope.input.variable);
})

.controller('Ctrl2', function($scope, Authorization) {
  $scope.input = Authorization;
  console.log($scope.input.variable);
 });

<input data-ng-controller="Ctrl1" type="text" ng-model="input.variable">

This worked for me. 这对我有用。 Thank you for your answers :) I was using ionic with angular. 谢谢你的答案:)我正在使用带角度的离子。 using just factory to store data and fetch worked like a charm. 使用工厂来存储数据和获取工作就像一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM