Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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!

share|improve this question
5  
Why are you trying to do this? $rootScope should not be used for holding data. Use a service. – R. Salisbury 59 mins ago
    
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 Jačionis 27 mins ago

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

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);
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.