【问题标题】:Which way of binding to dynamic radio buttons is better?哪种绑定到动态单选按钮的方式更好?
【发布时间】:2016-11-16 09:43:54
【问题描述】:

我在这里有两个版本,在 AngularJS 中完成同样的事情(我是新手,现在正在学习)。

代码如下。对于那些喜欢代码笔的人:oldnew

哪些更好,为什么?

此外,虽然旧版本依赖于函数和 ng-click,但新版本避免了这种情况。但是,如果不涉及“$scope.my”对象,我无法完成新版本所做的事情,即如果我将其设为“$scope.preference”,则建模似乎不起作用。有没有办法让我做到这一点?

当然,我遗漏了一些明显的东西,但我找不到什么。

var myApp = angular.module('myApp', []);
 myApp.controller('ExampleController', ['$scope',
   function($scope) {
     $scope.colors = ["blue", "red", "green"];

     //old way
     $scope.color = "";
     $scope.updateColor = function(input) {
       $scope.color = input;
     }
     
     //new way
     $scope.my = {preference: ''};
   }
 ]);
<head><script src="https://code.angularjs.org/1.5.8/angular.js"></script></head>

<body ng-app="myApp" ng-controller="ExampleController">
<!--https://docs.angularjs.org/api/ng/directive/ngValue -->

<h2>Old Way</h2>
<div ng-repeat="col in colors">
    <input type="radio" ng-model="color" value="col" name="favcol" ng-click="updateColor(col)">{{col}}<br>
</div>
<p>And the result is: {{color}}</p>

<hr />

<h2>New Way</h2>
<label ng-repeat="col in colors" for={{col}}>
    <input type="radio" ng-model="my.preference" ng-value="col" id="{{col}}" name="favcol">{{col}}<br>
</label>
<p>And the result is: {{my.preference}}</p>
</body>

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

点问题的发生是因为原语与非原语的范围继承行为。这是 Angular 的一个众所周知的错误/功能。没有点符号就无法使新方法工作(Angular 文档说你不应该这样做)。

查看这些以获得更多信息:

新旧方法的选择取决于个人喜好,尽管文档和大多数 Angular 开发人员会告诉你使用新方法 - 它看起来更精简并充分利用了 Angular 的双重绑定(想想如果外部因素改变了颜色,每种情况都会发生)。

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 2016-04-24
    • 2022-12-06
    • 2020-11-28
    • 1970-01-01
    • 2011-10-06
    • 2019-12-16
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多