0

I am a beginner at AngularJS, I tried the following code (from a tutorial) :

My view :

<div ng-app="app">
<div ng-controller="exempleCtrl">
   HELLO {{name}}!
</div>

My controller :

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

app.controller("exempleCtrl", function($scope) {
$scope.name = "World"
});

For a reason, I want to add some js code to my view that uses the value of "name", to do that I have to store it in a variable .. but this doesn't work

<script language="JAVASCRIPT">
    var name = {{name}};
</script>

but I don't know how to do that .. help please :)

3
  • you have it in your scope, why not put it in your controller anyway. Commented May 17, 2016 at 6:26
  • I need it in my view. Commented May 17, 2016 at 21:24
  • Could you explain why would you need it in your script tag? Commented May 18, 2016 at 2:39

3 Answers 3

2

This way is long but it works:

 <script type="text/javascript">
    setTimeout(function(){
        var name = angular.element(document.querySelector('[ng-controller="exempleCtrl"]')).scope().name;
        console.log(name)
    },5000)
 </script>
Sign up to request clarification or add additional context in comments.

2 Comments

It returns "undefined".
<script> run sooner than load ng-controller="exempleCtrl",That's why I've used Timeout,I know It's not perfect.
1

You cannot use interpolation ("{{variable}}") syntax in javascript. Is there a reason you are trying to do logic in a script tag rather than in the controller itself? Your controller is meant to be your connection between logic and your view so you shouldn't need to add any tags to your html to do that logic.

2 Comments

I understand, but I need to do that in my case.
I don't want to be quick to make assumptions since every situation is unique, so could you expand a little bit on why you need to do it in your view in a script tag? That may help find a solution.
1

If you really want to do this.

<div ng-app="app">
  <div id="myCtrl" ng-controller="exempleCtrl">
    {{name}}
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      var elem = document.getElementById('myCtrl');
      var name = angular.element(elem).scope().name;
      console.log(name);
    });

  </script>

See jsfiddle code

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.