-1

My question is in reference with this one. Pass JavaScript variable into AngualrJs ng-init

This was asked for passing a single javascript variable being passed to the angular controller. can someone let me know how can i pass several variables from a script to controller instead of a single variable ?

Community
  • 1
  • 1
Ayesha
  • 835
  • 4
  • 14
  • 33
  • 1
    The method of passing variables was explained in the other question. It is applicable both to single or multiple variables. – Fernando Pinheiro Oct 06 '15 at 20:55
  • first, don't use ng-init, that's not what it is for. second, why are you trying to handle variables from angular in the first place? – Claies Oct 06 '15 at 20:59
  • @Claies- The page has javascript code and we want to use angular now instead of jquery. so i was thinking of just passing the javascript variables to the controller and let the controller handle for specific models.... – Ayesha Oct 06 '15 at 21:07

2 Answers2

10

Assuming that your variables are not in any special scope...

window.var1 = true;
var var2 = "foo";
var3 = {foo: "bar"};

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.var1 = $window.var1;
  $scope.var2 = $window.var2;
  $scope.var3 = $window.var3;
}]);

Basically copy-pasted from linked question. Pass JavaScript variable into AngualrJs ng-init

Community
  • 1
  • 1
sg.cc
  • 1,726
  • 19
  • 41
3

Exactly the same way. Inject the $window service on your controller and all the variables outside angular mode will be available to the controller through:

$scope.ControllerVariable = $window.ScriptVariable
  • can you tell me if i could do the other way around too ? if i want to pass the angular variable to javascript variable ? – Ayesha Oct 07 '15 at 00:26
  • simple. jus got the answer after i tried it. just have to reverse it. – Ayesha Oct 07 '15 at 00:29
  • Actually, all `$scope.var` variables are available in the HTML through the `{{var}}` expression, inside the tag using the directive `ng-controller`. – Thiago Petrone Oct 07 '15 at 15:40