0

我有一种情况,我想使用$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变量的任何建议都会很棒!

4

2 回答 2

1

虽然不推荐,但如果你愿意,你可以通过以下方式进行

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

于 2015-12-10T12:29:04.380 回答
0

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

function MyCtrl($scope, $rootScope) {
    $scope.foo=null;
    $scope.doSomething = function () {
    $rootScope.foo=$scope.foo;
        alert("Hello, " + $rootScope.foo);
    }
}
于 2015-12-10T12:50:23.067 回答