我在这里有两个版本,在AngularJS中完成同样的事情(我是一个新手,刚刚学习)。哪种绑定动态单选按钮更好?
哪个更好?为什么?
另外,虽然旧版本依赖于函数和ng点击,但新版本可以避免这种情况。但是,如果不涉及“$ 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>
<title></title>
<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 -->
<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 />
\t \t <label ng-repeat="col in colors" for={{col}}>
\t \t \t <input type="radio" ng-model="my.preference" ng-value="col" id="{{col}}"
\t \t \t name="favcol">
\t \t {{col}}<br>
\t </label>
<p> And the result is: {{my.preference}}</p> </body>
公认的最佳做法是始终在“ng模型”中放置一个“点”。有关更多信息,请参阅AngularJS开发团队之一的[本视频](http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m)。另见[Angular Wiki:范围原型继承的细微差别](https://github.com/angular/angular.js/wiki/Understanding-Scopes)。 – georgeawg