我这里有两个版本,在 AngularJS 中完成同样的事情(我是新人,刚刚学习)。
哪一个更好,为什么?
此外,虽然旧版本依赖于函数和 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>
最佳答案
点问题的发生是由于基元与非基元上的范围继承行为造成的。这是 Angular 的一个众所周知的错误/功能。如果没有点符号,就没有办法让新方法工作(Angular 文档说你不应该这样做)。
请参阅以下内容以获取更多信息:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
Does my ng-model really need to have a dot to avoid child $scope problems?
http://blog.quarkslab.com/an-angular-introduction-and-things-to-keep-in-mind.html
旧方法与新方法的选择取决于个人喜好,尽管文档和大多数 Angular 开发人员会告诉你使用新方法 - 它看起来更精简并且充分利用了 Angular 的双重绑定(bind)(想想看如果外部因素改变了颜色,每种情况都会发生)。
关于javascript - 哪种方式绑定(bind)到动态单选按钮更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628671/