Insaf
Insaf

Reputation: 39

AngularJS : storing the value of a scope variable

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 :)

Upvotes: 0

Views: 1127

Answers (3)

Akbar Taghipour
Akbar Taghipour

Reputation: 334

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>

Upvotes: 2

Bon Macalindong
Bon Macalindong

Reputation: 1320

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

Upvotes: 1

sourdoughdetzel
sourdoughdetzel

Reputation: 664

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.

Upvotes: 1

Related Questions