$root scope with same variable with different values

702 views Asked by At

First of all excuse me if this doesn't make any sense.

I have a root-scope with two different values assigned in the same controller,and now i want to print those two values using that root-scope.....how can i achieve this

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

app.controller('MainCtrl', function($scope,$rootScope) {
  $rootScope.name = 'hello';
  $rootScope.name="world";
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

  
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
   
  </head>

  <body ng-controller="MainCtrl">
    <p>{{name}}</p>
  </body>

</html>

from the above i want to print hello world......

2

There are 2 answers

1
Tom Johnson On

You are overwriting the first value when you call $rootScope.name = "world";, I recommend you make an object instead like so;

$rootScope.helloWorld = {hello: "hello", world: "world"};

In the html;

<p>{{helloWord.hello}} {{helloWorld.world}}</p>
3
Roux On

What you want to do is

$rootScope.name = "hello";
$rootScope.name += " world";

In your code, you are just replacing the value.