I have two version here, of accomplishing the same thing in AngularJS (which I'm a new at, and just now learning).
The code is below. For those who prefer code-pen: old and new.
Which of those is better and why?
Also, while the old version relies on a function and ng-click, the new version avoids that. However, I haven't been able to do what the new version does without involving the "$scope.my" object, i.e. if I make it "$scope.preference" the modeling doesn't seem to work. Is there way that I could do that?
Surely, there's something obvious that I'm missing, but I couldn't find what.
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>