2013-06-28 113 views
0

场景: 我想要访问ng-Model对象(myRide)的属性(代码)。从HTML选择访问对象属性。

  1. 我试着通过

    <select ng-model = "myRide" 
        ng-change = "getCode(myRide.code)"> 
    

    ...在引用代码这样做,

    alert(parameter) //which should be myRide.code.

  2. 我也试图通过

    做到这一点
    <select ng-model = "myRide" 
        ng-change = getCode(myRide) 
    

    (注: 'myRide' 被传递,而不是 'myRide.code')......,在引用代码,

    alert(myRide.code).

myRide确实含有一种被称为 '代码' 属性,这是不未定义。

问题:两次尝试都不会产生想要的结果。


如何让它显示属性(代码)?

这里是的jsfiddle:http://jsfiddle.net/a2J6z/1/

回答

1

我更新了小提琴:

http://jsfiddle.net/a2J6z/3/

var ngApp = angular.module('ngAppl',[]); 

function aControlla($scope){ 

    $scope.myRide = "bus"; 

    $scope.getCode = function(car){ 
     alert(JSON.parse(car).code); 
    } 

    $scope.myGarage = [ 
     {Name: "Toyota 86", code:"1"}, 
     {Name: "Hyundai Genesis Coupe", code:"2"}, 
     {Name: "Nissan GTR", code:"3"}, 
     {Name: "Veyron", code:"4"} 
    ]; 
}; 

而且

<div ng-app="ngAppl"> 
    <div ng-controller="aControlla"> 

     <select ng-model="myRide" ng-change="getCode(myRide)"> 

      <option ng-repeat="car in myGarage">{{car}}</option> 
      <!--Note: value of myRide MUST be simply 'car' (not say, 'car.Code')--> 

     </select> 

     <br/> This shows that 'myRide' contains the property called 'Name', and importantly, 'code':<br/> {{myRide}} 




    </div> 
</div> 

基本上我不得不为它警告什么车myRide作为参数呃,它显示了JSON字符串,所以我添加了解析让它给我的代码。可以说我是AngularJS noob的更好的方式。

+0

干杯,你的方法效果很好。 (最终版本:http://jsfiddle.net/a2J6z/6/) – daCoda

2

更好的方法是重构视图。而不是在select中的选项中使用ng-repeat,请使用ng-options指令。然后,你可以将实际的对象绑定到模型上,而不仅仅是一个JSON字符串,这是你当前的小提琴正在做的事情。

您的新选择的模样

<select ng-options="car.Name for car in myGarage" ng-model="myRide" ng-change="getCode(myRide)"> 

</select> 

然后在你的控制器

$scope.getCode = function(car){ 
    alert(car.code); 
} 

更新的小提琴:

http://jsfiddle.net/a2J6z/5/

+0

ng-options确实比ng-repeat更方便。不过,我需要使用ng-repeat作为这个实例,我需要添加比myGarage更多的选项。 – daCoda