【发布时间】:2016-11-16 09:43:54
【问题描述】:
我在这里有两个版本,在 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>
【问题讨论】:
-
公认的最佳做法是始终在您的
ng-models中添加一个“点”。有关更多信息,请参阅 AngularJS 开发团队之一的THIS VIDEO。另见Angular Wiki: The Nuances of Scope Prototypal Inheritance。
标签: javascript angularjs