根据值

时间:2016-02-04 11:15:32

标签: angularjs

当我点击选择值列表时,我正在尝试相应地更改选择内的选定值。

我的第一个想法是尝试将这两个模型绑定在一起,但它并没有像我预期的那样工作。



(function(angular) {
  'use strict';
  angular.module('staticSelect', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.data = {
        options: [
          1, 2, 3, 4, 5, 6, 7
        ]
      };
      $scope.selectOption = function(option) {
        // To check that I get the correct value
        alert(option);
        // I want whenever I click on a value, it will toggle the select option box sync with that value
        $scope.option1 = option;
      }

    }]);
})(window.angular);

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-static-select-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="staticSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <select name="" id="">
      <option value="option" ng-repeat="option in data.options" ng-model="option1">{{option}}</option>
    </select>
  </form>
  <div ng-repeat="option in data.options">
    <span ng-model="option2" ng-click="selectOption(option)">{{option}}</span>
  </div>
</div>
</body>
</html>

<!-- 
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

你可以试试这个

<select ng-options="c.Id as c.Name for c in data" ng-model="option1">

所以在option1中,您将获得选择项目的 ID 控制器

angular.module('staticSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
  $scope.option1 = 1;
  $scope.data = [{"Id":1,"Name":"Theme1"},
                 {"Id":2,"Name":"Theme2"},
                 {"Id":3,"Name":"Theme3"}];
}]

答案 1 :(得分:1)

使用

修改select语句
 <select name="" id="" ng-model="option1">
  <option value="option" ng-repeat="option in data.options" ng-selected="option1 == option">{{option}}</option>
</select>

希望这会对你有所帮助。