简体   繁体   English

在Angular JS中,如何在定义的函数之外检索$ scope值

[英]How to retrive a $scope value outside the function it is defined, in Angular JS

I have the Controller 我有控制器

function loginController($scope, $http, $cookieStore, $location) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
    $scope.log_me = function() {
    $scope.login_me = [];
    var login_un = $scope.uservals;
    var login_pwd = $scope.passvals;
    var logs_me = "api call here";
    $http.get(logs_me)
        .success(function(response) {
            $cookieStore.put('token', response.token);
            $cookieStore.put('ex_Id', response.ExId);
            $cookieStore.put('Cont_Id', response.contactId);
            $cookieStore.put('email', response.email);
            $cookieStore.put('name', response.name);
            $scope.log_sess = response;
            $scope.sess_id= response.ss_id;
            alert($scope.sess_id);
            if (response.status == "failure, invalid username or password") {
                $('.login_error').show();
                $('.login_error').html('Invalid username or password');
                $('.login_error').delay(4000).fadeOut();
                $('.loading').hide();
            } else {
                $location.path('/dashboard');
            }
        });
  }

} }

I have used the above controller in my login page and it is working fine. 我在登录页面中使用了上面的控制器,它工作正常。 Now i want to use the same controller in another template and retrieve the value "$scope.sess_id" 现在,我想在另一个模板中使用相同的控制器,并检索值“ $ scope.sess_id”

My Template is 我的模板是

 <div class="page" >
 <style>
 #report_loader object {
   width: 100%;
   min-height: 700px;
   width:100%;
   height:100%;
 }
 </style>
 <div class="loading"> </div>
 <section class="panel panel-default" data-ng-controller="loginController">
        <div class="panel-body" style=" position: relative;">
            <div id="report_loader" style="min-height:600px;">
            {{sess_id}}
             <script type="text/javascript">
                $("#report_loader").html('<object data="https://sampleurl/contact/reports/members/sorted_list.html?ss_id=' + sess_id+' />');
            </script>
            </div>
            </div>
    </section>
 </div>

I am unable to retrieve the value {{sess_id}} here. 我无法在此处检索值{{sess_id}}。 What should be done so that i can bring this value in my template 应该怎么做才能将这个值带入模板

You're routing the user to the "dashboard" route upon successful log in. Even though it might feel like you're using the same "loginController" for both login and dashboard, it will be an entirely new instance of both the controller and $scope. 您将在成功登录后将用户路由到“仪表板”路由。即使您可能感觉登录名和仪表板都使用相同的“ loginController”,但这将是控制器和控制器的全新实例。 $ scope。 Which is why the {{sess_id}} is not displaying on the dashboard template. 这就是{{sess_id}}未显示在仪表板模板上的原因。

If you're following an MVC-like pattern of AngularJS, ideally you want to be creating a new controller for your dashboard template. 如果您遵循的是类似MVC的AngularJS模式,则理想情况下,您希望为仪表板模板创建一个新的控制器。 See explanation: https://docs.angularjs.org/guide/controller#using-controllers-correctly 参见说明: https//docs.angularjs.org/guide/controller#using-controllers-正确

So, I would create a DashboardCtrl and share the sess_id between the two. 因此,我将创建一个DashboardCtrl并在两者之间共享sess_id。 There are plenty of examples out there of how to share data between controllers: 关于如何在控制器之间共享数据有很多示例:

Hope it helps. 希望能帮助到你。

I would use the rootScope approach, but an easier way to do that is to simply create a 'global' variable. 我将使用rootScope方法,但更简单的方法是创建一个“全局”变量。

In your main controller (not your login controller), define a global scope variable like this: 控制器(而不是登录控制器)中,定义一个全局范围变量,如下所示:

$scope.global = {};

Then in your login controller, modify your session id to use the global variable: 然后在登录控制器中,修改会话ID以使用全局变量:

$scope.global.sess_id= response.ss_id;
alert($scope.global.sess_id);

Then in your html: 然后在您的html中:

<div id="report_loader" style="min-height:600px;">
{{global.sess_id}}

It's simple and works like champ. 它很简单,就像冠军。

I would create a service : 我会创建一个服务:

services.sessionService = function(){

    var sessionID = null;

    this.setSessionID = function(id){
         sessionID = id; 
    }
    this.getSessionID = function(){
        return sessionID;
    }
}

then in your controller : 然后在您的控制器中:

$scope.sess_id= response.ss_id;
alert($scope.sess_id);
sessionService.setSessionID( $scope.sess_id );

and in your dashboard controller : 并在您的仪表板控制器中:

$scope.sess_id = sessionService.getSessionID();

Approaches 途径

Your question's answer has many approach. 您问题的答案有很多方法。 They are: 他们是:

  1. Using value or service , you can call it wherever your controllers need them. valueservice ,您可以在controllers需要它们的任何地方调用它。
  2. Using $rootScope , this is very common and easy to use. 使用$rootScope ,这是非常常见且易于使用的。 Just define your $rootScope inside your main controller or whatever controller that called first and then you can call it from other controllers like any $scope behavior. 只需在main controller或首先调用的任何控制器中定义$rootScope ,然后您就可以像其他其他$scope行为一样从其他控制器中调用它。
  3. Using $controller service or usually called controller inheritance . 使用$controller服务或通常称为controller inheritance Define this in controller function's parameter, then type $controller('ControllerNameThatIWantToInheritance', {$scope:$scope}); 在控制器函数的参数中定义它,然后键入$controller('ControllerNameThatIWantToInheritance', {$scope:$scope});

Maybe any other approach can be use to it. 也许可以使用任何其他方法。 Each of them have strength and weakness. 他们每个人都有优点和缺点。

Examples: 例子:

using value 使用价值

.value('MyValue', {
  key: null
})

.controller('MyCtrl', function ($scope, MyValue) {
  $scope.myValue = MyValue;
})

you can modified MyValue from service too 您也可以通过服务修改MyValue

using $rootScope 使用$rootScope

.controller('FirstCtrl', function ($scope, $rootScope) {
  $rootScope.key = 'Hello world!';
})

.controller('SecondCtrl', function ($scope, $rootScope) {
  console.log($rootScope.key);
})

will print 'Hello World', you can also use it in view <div>{{key}}</div> 将打印“ Hello World”,您也可以在视图<div>{{key}}</div>使用它

using $controller 使用$controller

.controller('FirstCtrl', function ($scope) {
  $scope.key = 'Hello world!';
})

.controller('SecondCtrl', function ($scope, $controller) {
  $controller('FirstCtrl', {$scope:$scope});
})

Second controller will have $scope like first controller. 第二个控制器将像第一个控制器一样具有$scope

Conclusion 结论

In your problem, you can split your controller for convenient. 在遇到问题时,可以拆分控制器以方便使用。 But if you dont' want to, try to define $scope.sess_id first. 但是,如果您不想这样做,请尝试首先定义$scope.sess_id It will tell the Angular that your sess_id is a defined model, and angular will watch them (if you not define it first, it will be 'undefined' and will be ignored). 它会告诉Angular您的sess_id是已定义的模型,而angular会监视它们(如果您不首先定义它,它将是'undefined'并将被忽略)。

function loginController($scope, $http, $cookieStore, $location) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
$scope.sess_id = null                   //<- add this
$scope.log_me = function() {
  $scope.login_me = [];
  var login_un = $scope.uservals;
  var login_pwd = $scope.passvals;
  var logs_me = "api call here";
  $http.get(logs_me)
    .success(function(response) {
        $cookieStore.put('token', response.token);
        $cookieStore.put('ex_Id', response.ExId);
        $cookieStore.put('Cont_Id', response.contactId);
        $cookieStore.put('email', response.email);
        $cookieStore.put('name', response.name);
        $scope.log_sess = response;
        $scope.sess_id= response.ss_id;
        alert($scope.sess_id);
        if (response.status == "failure, invalid username or password") {
            $('.login_error').show();
            $('.login_error').html('Invalid username or password');
            $('.login_error').delay(4000).fadeOut();
            $('.loading').hide();
        } else {
            $location.path('/dashboard');
        }
    });
  }
}

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

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