简体   繁体   English

在不同范围的angularJs中使用变量

[英]Using variable in different scope angularJs

I have this controller in angularJs 我在angularJs中有这个控制器

.controller('MapCtrl', function($scope, $http, $rootScope) {
  $scope.mappa={};
  var curPos;

  if (navigator.geolocation)
      navigator.geolocation.getCurrentPosition(success);

    function success(pos) {
      var crd = pos.coords;
      curPos = crd.latitude;
    };

    console.log(curPos);
})

The conole.log gives me an undefined. conole.log给了我一个未定义的。 I know that this could be an obvious question for someone but how can I solve this? 我知道这对某人可能是一个显而易见的问题,但是我该如何解决呢?

EDIT 编辑

Sorry guys, I wasn't so clear: I need to use the curPos var outside the function. 抱歉,我不清楚:我需要在函数外部使用curPos var。 Once it has been enhanced I need to read its value everywhere in the controller. 增强后,我需要在控制器中的任何位置读取其值。

navigator.geolocation.getCurrentPosition is aysnchronous, so by the time your success function is executed, your console.log(curPos) is getting executed, hence undefined. navigator.geolocation.getCurrentPosition是不同步的,因此在执行成功函数时,console.log(curPos)将被执行,因此未定义。 Just put console.log(curPos) inside your success function. 只需将console.log(curPos)放入您的成功函数中即可。

.controller('MapCtrl', function($scope, $http, $rootScope) {
   $scope.mappa={};
   var curPos;

  if (navigator.geolocation)
  navigator.geolocation.getCurrentPosition(success);

   function success(pos) {
      var crd = pos.coords;
      curPos = crd.latitude;
      console.log(curPos);
   };


})

I assume the 'getCurrentPosition' is some sort of service call and hence your success call back is being called asynchronously (after the promise returned from service). 我假设“ getCurrentPosition”是某种服务调用,因此您的成功回调是异步调用的(在从服务返回的承诺之后)。

So, move your logic, where you are using 'curPos' variable, to your success call back function. 因此,将您使用'curPos'变量的逻辑移到成功回调函数中。 There you will have the updated value of 'curPos'. 在那里,您将拥有'curPos'的更新值。

.controller('MapCtrl', function($scope, $http, $rootScope) {
    $scope.mappa = {};
    var curPos;

    if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(success);

    function success(pos) {
        var crd = pos.coords;
        curPos = crd.latitude;
        console.log(curPos); // would be a defined value here
        // your logic goes here
    };

    console.log(curPos); // would be undefined as it is being called before the execution of success call back function
})

It also depends on the cases you need to work on. 它还取决于您需要处理的情况。

  1. If this value of 'curPos' is fetched once : 如果一次获取此“ curPos”值

    a. 一种。 At the time of app start up - then fetch this value in somoe home controller or the parent / abstract controller and save it in some factory (shared data service), which then can be fetched from any of the controllers as when required. 在应用启动时 -然后在somoe家用控制器或父/抽象控制器中获取此值,并将其保存在某个工厂(共享数据服务)中,然后可以根据需要从任何一个控制器中获取该值。

    b. At the time of page load - then this can be fetched before the page load using anguler ui router states and resolves. 在页面加载时 -然后可以使用anguler ui路由器状态和解析在页面加载之前获取此信息。 Refer http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/ for more details. 有关更多详细信息,请参见http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/

  2. If the value needs to be updated every now and then - in this case you will have to move your every logic (which uses this variable) to success call back (can implement multiple call backs depending upon the variation in logic), by this you would be explicitly synchronizing this scenario. 如果需要不时更新该值 -在这种情况下,您将必须将您的每个逻辑(使用此变量)移动到成功回调(可以根据逻辑的变化实现多次回调),通过此操作将明确同步这种情况。

Use $scope.$apply to update your scope in an async method no handled by Angular framework. 使用$scope.$apply以Angular框架不处理的异步方法更新范围。

Here is a working example : 这是一个工作示例:

Plunker : https://plnkr.co/edit/xiv33CunDZrb06PvfFyU 柱塞: https ://plnkr.co/edit/xiv33CunDZrb06PvfFyU

script.js 的script.js

angular.module('app', []);

angular.module('app').controller('SampleController', function ($scope) {
    var ctrl = this;

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
          // On success
          function(pos) {
            console.log(pos)
            $scope.$apply(function() {
                $scope.coords = pos.coords;
            })
          }, 
          // On error
          function(err) {
            console.error(err)
          }
      );
    }
});

index.html 的index.html

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="scripts.js"></script>
</head>

<body ng-controller="SampleController as ctrl">

<p>
    latitude: {{coords.latitude}} <br/>
    longitude: {{coords.longitude}} <br/>
</p>

</body>
</html>

Since its an async process, if you print the var without waiting success of getCurrentPosition, it will be undefined. 由于它是异步过程,因此如果在不等待getCurrentPosition成功的情况下打印var,它将是未定义的。 You have to print it after this callback (or inside it). 您必须在此回调之后(或在其中)打印它。 Futhermore, if you want access to this var, first you have to check if its defined, if its not, wait for it. 此外,如果要访问此var,首先必须检查其是否已定义,否则请等待。 You can play with angular $timeout and vars to print the console when the var is ready. var准备好后,您可以使用angular $ timeout和vars来打印控制台。

I don't know exactly why, but I finally make it work just by using angular.copy 我不知道为什么,但是我最终仅通过使用angular.copy使其工作

    var curPos = {};

      navigator.geolocation.getCurrentPosition(function(pos) {
        var tmpPos = {
                  lat: pos.coords.latitude,
                  lng: pos.coords.longitude
        }

        angular.copy(tmpPos, curPos);
      });

      console.log(curPos);

I had to put all the code which uses that var inside the success function. 我必须将所有使用该var的代码放入成功函数中。 Thanks to everyone :) 谢谢大家 :)

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

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