我想要使用 $ 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 变量的任何建议都会很棒!
答案 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);
}
}