0

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?

1
  • 1
    angular.element(document.getElementById("mainBody")).scope().myVariable should work - what is the output Commented May 27, 2014 at 20:27

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

$window.myVariable = $scope.myVariable;

2 Comments

I was trying to do that, but it didn't work. ... samplefunction( $window.myVariable )
Is that function in your vanilla JS? Or in Angular?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.