user3681259
user3681259

Reputation: 1

Accessing AngularJS variable in view?

Consider basic AngularJS application with just one controller. Inside the controller I have set-up "myVariable" to hold a value "Test".

I am given an inline JavaScript code in the view and I need to call a function samplefunction which takes a parameter using myVariable.

/* Controllers */

angular.module('myApp.controllers', [])
    .controller('MainCtrl', ['$scope', function($scope) {

        $scope.myVariable = "Test";

    });

In the view, in the html file, this is what I need to do:

<script type="text/javascript">

    var param1 = {{myVariable}};   /* <-- how to make this work?  */
    samplefunction( param1 );   

</script>

It doesn't work though. I just need to assign myVariable value to the param1. I also tried something like:

...
var param1 = angular.element(document.getElementById("mainBody")).scope().myVariable
...

But this didn't work either. Please, note that I cannot touch the given JS code that I am calling in the view.

Anyone knows how to solve this simple issue?

Upvotes: 0

Views: 2090

Answers (3)

Dalorzo
Dalorzo

Reputation: 20024

From my POV what you are doing shouldn't be done. The closest correct approach should be:

Setting your view with a value in the way angular was meant to be used:

<input type="text" ng-model="myVariable" id="myVar" />

and iff you want to you get your var value get it from the view like:

<script type="text/javascript">  
    var param1 = document.getElementById("myVal").value;
    samplefunction( param1 );   
</script>

Online Demo

Upvotes: 1

TGH
TGH

Reputation: 39278

What about binding the scope variable to a data-something attribute on an element in your view, and then pull it using Jquery in your external script tag?

<script type="text/javascript">  
    var param1 = $("#someId").data("myValue");
    samplefunction( param1 );   
</script>

Upvotes: 0

Steve
Steve

Reputation: 569

Pass the var to $window to expose it to your JS.

$window.myVariable = $scope.myVariable;

Upvotes: 0

Related Questions