Angular 将输入值传递给 $rootScope 变量

Angular pass input value to $rootScope variable

我有这样的情况,我想使用 $rootScope 变量并用输入字段中输入的值更新它的值。我将情境代码缩短为 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>

脚本:

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

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

任何关于如何将输入值传递给 $rootScope 变量的建议都很棒!

虽然不推荐,但如果您愿意,可以按照以下方式进行

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

脚本

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

当文本字段的值更改时 onFooChange 调用函数并将值存储到 $rootScope.

这是一种不使用 ng-change 的方法:

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