Angular js将所选对象传递给下拉/选择的更改事件:

时间:2016-06-29 05:16:13

标签: javascript angularjs

Plunkr: http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview

我正在尝试将下拉列表的选定项目传递给控制器​​中的某个功能。

然而,我认为这是未定义的。

HTML:

<!DOCTYPE html>
<html>

  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>

    <div ng-app="MyApp" ng-controller="MyController">
        <select ng-model="ddlFruits" 
        ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
            ng-change="GetValue(fruit)">
        </select>
    </div>

  </body>

</html>

脚本:

var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
    $scope.Fruits = [{
        Id: 1,
        Name: 'Apple'
    }, {
        Id: 2,
        Name: 'Mango'
    }, {
        Id: 3,
        Name: 'Orange'
    }];

    $scope.GetValue = function (fruit) {
        alert(fruit);
    }
});

2 个答案:

答案 0 :(得分:1)

你好HTMLM改变了这个

ng-change="GetValue(ddlFruits)"
从控制台

您将获得所选

的ID
<select ng-model="ddlFruits" 
        ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
            ng-change="GetValue(ddlFruits)">
        </select>

答案 1 :(得分:0)

这会让你获得成果

HTML

 <select ng-model="ddlFruits" 
    ng-options="fruit.Id as fruit.Name for fruit in Fruits track by fruit.Id"
        ng-change="GetValue(this)">
    </select>

  $scope.GetValue = function (val) {
    alert(val.Fruits[val.ddlFruits].Name);
  }

这将为您提供选定的值

$scope.GetValue = function () {
    alert($scope.ddlFruits);
  }