角度传递输入值为$ rootScope变量

时间:2015-12-10 12:14:46

标签: javascript html angularjs angularjs-rootscope

我想要使用 $ 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>

SCRIPT:

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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