繁体   English   中英

更新angularjs服务中的单选值

[英]update radio value in angularjs service

我在ControllerA中有一个单选按钮值列表,该列表以ng-repeat打印在视图中。 该列表来自服务。 现在,我要检查在ControllerB中选择了哪个单选按钮。

如何获得当前选择的值?

我是否需要在ControllerA中添加$ watch函数并以这种方式更新服务?

还是有其他方法可以将变量从控制器基本绑定到服务中的变量?

无需设置$watch 这都是关于控制器之间共享状态的。

使用Javascript

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

HTML

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

您可以在插件中看到它的实际效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM