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!

3
  • 5
    Why are you trying to do this? $rootScope should not be used for holding data. Use a service. Commented Dec 10, 2015 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. Commented Dec 10, 2015 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. Commented Dec 10, 2015 at 13:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

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.