0

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>
Julix
  • 598
  • 1
  • 9
  • 20
  • The accepted best practice is to always put a "dot" in your `ng-models`. For more information, see [THIS VIDEO](http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m) by one of AngularJS development team. See also [Angular Wiki: The Nuances of Scope Prototypal Inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes). – georgeawg Nov 16 '16 at 09:58

1 Answers1

2

The dot issue happens because of scope inheritance behaviour on primitives vs. non-primitives. It's a well-known bug/feature of Angular. There is no way to make the new method work without the dot notation (and the Angular docs say you shouldn't).

See these for more info:

The choice of old vs. new method comes down to personal preference, although the docs and the majority of Angular devs will tell you to use the new method - it looks leaner and makes full use of Angular's double-binding (think what would happen in each case if something external modifies the color).

Community
  • 1
  • 1
Shomz
  • 37,421
  • 4
  • 57
  • 85