我在ControllerA中有一个单选按钮值列表,该列表以ng-repeat打印在视图中。该列表来自服务。现在,我要检查在ControllerB中选择了哪个单选按钮。
如何获得当前选择的值?
我是否需要在ControllerA中添加$ watch函数并以这种方式更新服务?
还是有其他方法将变量从控制器基本绑定到服务中的变量?
无需设置$watch
; 这都是关于控制器之间共享状态的。
var app = angular.module('app', []);
app.factory('myState', function() {
// For this example I'm just returning the state directly, but it can also
// be returned from some function or even some backend api. Just remember
// that factories (services/providers) are singletons and will point always
// to the same instance within your app.
return {
chickenEgg: 'egg'
};
});
app.controller('ControllerA', function($scope, myState) {
$scope.formData = myState;
});
app.controller('ControllerB', function($scope, myState) {
$scope.result = myState;
});
<div ng-controller="ControllerA">
<h2>ControllerA</h2>
<form class="form">
<label>Chicken or the Egg?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="chicken" ng-model="formData.chickenEgg">Chicken
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chickenEgg" value="egg" ng-model="formData.chickenEgg">Egg
</label>
</div>
</div>
</form>
</div>
<div ng-controller="ControllerB">
<h2>ControllerB</h2>
<pre><code>result = {{ result | json }}</code></pre>
</div>
您可以在此插件中看到它的实际效果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句