0

Perhaps my brain is still not fully functional this morning, but what's the best or proper way to get a variable from a template/view into a controller in Angular?

Say in my view I have defined var a = 'something', and I need to access that value inside the controller.

I could do passVariable(a) on ng-init, and inside the controller have something like

$scope.passVariable = function(param){
  $scope.a = param; 
}

But obviously that doesn't work, and the method doesn't seem very right either ;-)

Pim
  • 756
  • 1
  • 7
  • 18
  • 1
    Where the `var a` is defined? Instead of `var a ..` you can use `.value([..])` service of angularjs and inject into controllers. – Rahil Wazir Nov 12 '14 at 11:19
  • It's defined in the view. It needs to be, since the variable can change from view to view. Calling `.value(...)` inside the view doesn't work, how would I go about it? – Pim Nov 12 '14 at 13:46

2 Answers2

0

You can do something like this.

After you assign angular module to a variable

 var myApp = angular.module('myApp', []);
 myApp.value('a', 'something');

then inject into the controller

myApp.controller('myController', ['a','$scope', function (a,scope) {
  $scope.a = a;

}]);

So in your view, for example say 'a' is a user name that you want to show to the user

 <div ng-controller="myController">

     <div> User Name: {{a}} </div>

 </div>

this will render as

  User Name : something
ssayyed
  • 766
  • 1
  • 8
  • 13
  • It works when I do `myApp.value('a', 'something');` inside the controller, but how can I do it in the view? – Pim Nov 12 '14 at 13:06
  • Thank you for the edit, but like stated in the question the variable must be defined inside the view, since it changes from view to view. (e.g. `var a = 'something'`). Displaying the value of the variable isn't the problem. – Pim Nov 12 '14 at 13:49
0

Ok, so it turns out my first idea wasn't too bad after all. I've done exactly what I was describing in my question, except the variable a needed to be defined within angular context, or passed directly into the function. For some reason var a = 'something' (in the view) wasn't getting picked up.

So the following didn't work:

<script>
  var a = something;
</script>
<div ng-controller="myController" ng-init="passVariable(a)">
</div>

but with ng-init="passVariable('something')", it does.

In the controller:

$scope.passVariable = function(param){
  $scope.a = param; 
}


And here's another possible answer using $window: Pass JavaScript variable into AngualrJs ng-init

With the following example: http://codepen.io/qwertynl/pen/jqIrK

Community
  • 1
  • 1
Pim
  • 756
  • 1
  • 7
  • 18