【问题标题】:Angular Radio Input unchecked on load with ng-value使用 ng-value 加载时未选中 Angular Radio Input
【发布时间】:2016-11-21 16:17:31
【问题描述】:

我正在使用 ng-value 将无线电输入值设置为对象,因此当该值与 ng-model 对象匹配时,应该会检查无线电。这是一个例子和 plunker。

<script>
angular.module('test', [])
.controller('testController', ['$scope', function($scope) {

  $scope.Obj = {
    "id": "1",
    "value": "green"
  };
  $scope.ObjTwo = {
    "id": "2",
    "value": "red"
  };
  $scope.ObjThree = {
    "id": "3",
    "value": "blue"
  };

  $scope.modelObj = {
    "id": "3",
    "value": "blue"
  };

}]);
</script> 

<form name="myForm" ng-controller="testController">
  <label>
   <input type="radio" ng-model="modelObj" ng-value="Obj">
   {{Obj}}
  </label><br/>
  <label>
    <input type="radio" ng-model="modelObj" ng-value="ObjTwo">
    {{ObjTwo}}
  </label><br/>
  <label>
    <input type="radio" ng-model="modelObj" ng-value="ObjThree">
    {{ObjThree}}
  </label><br/>

  color = {{modelObj}}<br/>

https://plnkr.co/edit/aAISUTEqdGkpVrEJt0uq?p=preview

当模型对象更新为相关对象时,单击单选按钮似乎可以正常工作。但是为什么没有在加载时检查第三个无线电输入(objThree)?我想是因为 $scope.Objthree 等于控制器中设置的 $scope.modeObj ,所以它会检查无线电输入?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    工作示例:https://plnkr.co/edit/J3QQM0z0nSC9KulHzQGI?p=preview

    试试$scope.modelObj = $scope.ObjThree;。这会将$scope.modelObj 的引用设置为等于ObjThree 对象,而不是仅仅使用恰好具有相同属性的新引用创建一个新对象。一般来说,JavaScript 使用引用相等来比较对象,并且只使用值相等来比较基本数据类型,例如数字和字符串。

    【讨论】:

      【解决方案2】:

      您可以在ngInit中设置:

      ng-init="modelObj = ObjThree"
      

      可能是:

      <form name="myForm" ng-controller="testController" ng-init="modelObj = ObjThree">
      

      【讨论】:

        猜你喜欢
        • 2013-10-17
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 2015-07-26
        • 1970-01-01
        • 2021-10-09
        • 2018-07-30
        相关资源
        最近更新 更多