0

I have situation where I want to use $rootScope variable and update its value with the one entered in input field. I have sitauation code shortened to this DEMO:

HTML:

<div ng-controller="MyCtrl">
    <input type="text" ng-model="foo" placeholder="Enter something" />
    <input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>

SCRIPT:

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

function MyCtrl($scope, $rootScope) {
    $rootScope.foo = null;
    $scope.doSomething = function () {
        alert("Hello, " + $rootScope.foo);
    }
}

Any suggestions on how to pass input value to $rootScope variable would be great!

Mindaugas
  • 1,173
  • 5
  • 15
  • 31
  • 5
    Why are you trying to do this? `$rootScope` should not be used for holding data. Use a service. – R. Salisbury Dec 10 '15 at 12:15
  • I do actually need to share this value between two controllers and I have 0 practice with services, as I am new to angular. – Mindaugas Dec 10 '15 at 12:48
  • You can use a service just like you're using `$rootScope`, just create a property on the service that holds `foo` and assign to it. Services are singletons so they persist through the lifetime of the app. – R. Salisbury Dec 10 '15 at 13:22

2 Answers2

1

Although not recommended, Still if you want you can do it the following way

<div ng-controller="MyCtrl">
    <input type="text" ng-model="foo" placeholder="Enter something" ng-change="onFooChange()" />
    <input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>

Script

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

function MyCtrl($scope, $rootScope) {
    $rootScope.foo = null;

    $scope.onFooChange = function(){
     $rootScope.foo = angular.copy($scope.foo);
    }

    $scope.doSomething = function () {
        alert("Hello, " + $rootScope.foo);
    }
}

When the value of text field is changed onFooChange function is called and the value is stored into $rootScope.

Vivek
  • 11,938
  • 19
  • 92
  • 127
0

Here is an approach without using ng-change:

function MyCtrl($scope, $rootScope) {
    $scope.foo=null;
    $scope.doSomething = function () {
    $rootScope.foo=$scope.foo;
        alert("Hello, " + $rootScope.foo);
    }
}
v1shnu
  • 2,211
  • 8
  • 39
  • 68