0

I am trying to pass values which I am getting from an array from JavaScript file and pushing it to angularJS by using a global variable

In angular file, I am trying to get those values by accessing global variable like but it returns me undefined however I ran

How can I access this values in my controll

v. josh
  • 119
  • 1
  • 1
  • 12
  • 3
    If the variable is global (I mean, window-level global), then it is necessarily available anywhere in your app, including inside your controllers. – Jeremy Thille Sep 06 '17 at 10:36
  • 1
    First, abc function is wrong declared, you forgot () before the { – Kalamarico Sep 06 '17 at 10:41
  • 2
    @v.josh Can you please post [**Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve)? Since doing this `var globalarray=[]; function abc (){ var array1 =[4,5]; globalarray.push(array1)}; abc(); (function() {console.log(globalarray[0]);})();` will give the proper output: `[4, 5]`. – Stanislav Kvitash Sep 06 '17 at 10:47
  • Your approach is totally incorrect. You have to wrap your code for OSM with [`directive`/`component`](https://docs.angularjs.org/guide/directive). In this case you will not have problems like you've mentioned in your question. – Stanislav Kvitash Sep 07 '17 at 07:13

4 Answers4

1

By the example you have shown above.

  1. You are not pushing the values in the globalarray. by not calling the abc() function.

  2. If your globalarray variable is window level global it would be available from anywhere in your angular app.

Please observe the behavior in the fiddle I've made for demonstation. I've also made a plunk so you would understand clearly.

Fiddle

var globVar = [12 ,33];
var myApp = angular.module('myApp', []);    
myApp.controller('MyController', function($scope) {      
  $scope.globVar = globVar;
}); 

Update

Since the data came in a callback you needed to re run the digest cycle and update the variable. Please observe this fiddle as it has your coordinates init.

// we got the cords
var cords = ol.proj.transform(coordinates, 'EPSG:3857', 'EPSG:4326');

// we get the scope from the element that has the controller binded to it.
var scope = angular.element(document.getElementById("MainWrap")).scope();

// we call a digest cycle of angular to update our scope variable sinse it comes in a callback when angular is loaded
scope.$apply(function () {
   scope.updateCords(cords);
});

Working Fiddle

Hope now it helps.

M. Junaid Salaat
  • 3,765
  • 1
  • 23
  • 25
  • @v.josh Please see the updated answer and the fiddle attached to it. I've tried to be as descriptive a s possible. – M. Junaid Salaat Sep 06 '17 at 16:42
  • can you please check the plunker which i have updated then you can get the exact idea what i want – v. josh Sep 07 '17 at 06:15
  • @M.JunaidSalaat Using `scope()` method is not recommended and will not work [when running in production](https://docs.angularjs.org/guide/production) with `$compileProvider.debugInfoEnabled(false);`. – Stanislav Kvitash Sep 07 '17 at 07:10
  • @v.josh have you checked out this plunker? https://plnkr.co/edit/rpdLqfNgVyXTJ4GOj61f?p=preview – M. Junaid Salaat Sep 08 '17 at 08:50
  • actually my controller loading first before javascript file so when i ran my file it gives me value as undefined. – v. josh Sep 08 '17 at 15:03
  • @v.josh Can you make an accurate representation of your code in a plunker so I can debug and suggest you a solution. – M. Junaid Salaat Sep 08 '17 at 15:36
1

Try this:

$scope.globalarray = [];

function abc() {
   var array = [4,5]
   angular.forEach(array,function(k,v){
     $scope.globalarray.push(k); 
  })

}
Nikita
  • 437
  • 2
  • 12
1

have a look at this link:

AngularJS access scope from outside js function

you can think of it in a different way, once you have access to the scope, you simply call a setter method inside the controller with the data in your array and then you can do whatever you need. I have used this approach in a project and it works quite well.

example :

//externalScope is a global variable declared in the angular controler //this is a way to access the controller and trigger methods from outside of angular //all we want is to signal to angular that some data has been changed so it can do something. in my example selectedUserValue is the data bit I am passing to the controller.

if (externalScope) {
    externalScope.$apply(function () {
        externalScope.selectUser(selectedUserValue);
    });
}

this code lives outside of the controller wherver you try to call the scope method with some data

now in the actual controller we have something like this:

    var externalScope;

    (function () {
   controller code

somewhere in the controller :

externalScope = $scope; //this exposes the scope to the outside world

notice how the externalScope variable is declared outside of the controller so it will be global.

After this just code whatever you need in the angular method that you call from the outside.

in my case it's a setter and then it calls something else which makes use of that data:

$scope.selectUser = function (userID) {
            if (userID && userID !== $scope.selectedUserID) {
                $scope.selectedUserID = userID;
                $scope.loadUserRecords();
            }
        };

Hope this makes sense. Disclaimer ... This isn't what I call something trivial and should only be used if you really have no other option!

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32
  • i have tried by using $apply functron but still its not working can you please check plunker which i have updated. – v. josh Sep 07 '17 at 06:55
-2

Global variables is not a good idea, maybe you need to interact with another web or framework.

Is you should ouse a global variable, you can declare with a special script in index.html

<script type="text/javascript">    
 let globalarray; 
</script>

You also could asign the globalarray to a property of window

window.globalarray

Or $rootScope.

Pako Navarro
  • 168
  • 1
  • 2
  • 9
  • i already tried this one $scope.globalarray=$window.globalarray; console.log($scope.globalarray) but still geting undefined. and when i have checked the length of the console.log(globalarray.length) it returns me 0 but console.log(globalarray) return me that 2 values – v. josh Sep 06 '17 at 10:49