2016-11-16 35 views
0

我在这里有两个版本,在AngularJS中完成同样的事情(我是一个新手,刚刚学习)。哪种绑定动态单选按钮更好?

代码如下。对于喜欢代码笔的人:oldnew

哪个更好?为什么?

另外,虽然旧版本依赖于函数和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>

+0

公认的最佳做法是始终在“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

回答

2

的点问题是因为对原语与非原语范围继承行为。这是Angular的一个众所周知的bug /功能。如果没有点符号,没有办法让新的方法工作(并且Angular文档说你不应该这样做)。

更多信息请参见以下:

老与新方法的选择归结为个人的预尽管文档和大多数Angular开发人员会告诉您使用新的方法 - 它看起来更精简并充分利用了Angular的双重绑定(想想如果外部修改颜色,每种情况都会发生什么)。

+0

感谢您的解释和高质量的链接:) – Julix

+0

不客气,很高兴我可以帮助! :) – Shomz