ngOptions选择导致内容更改的位置

时间:2014-05-09 05:46:34

标签: angularjs

我很难使用ngOptions,因为我需要一个标签有多个值,选择一个值将决定在视图中评估的内容。例如,如果标签为Boy,则值可以是hehim。然后,取决于句子将取决于是否使用hehim

HTML:

<!DOCTYPE html>
<html ng-app="myTest">
  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-controller="TestController">
    <select ng-model="test" ng-options="gen.pick group by gen.gender for gen in gender">
    </select>
    <p>{{ gender.value }} is a girl</p>
    <p>{{ gender.value }} is a boy</p>
  </body>
</html>

代码:

angular.module('myTest', []).controller('TestController', function($scope) {
    $scope.gender = [
      { pick: 'she', gender: 'female'},
      { pick: 'her', gender: 'female'},
      { pick: 'he', gender: 'male'},
      { pick: 'him', gender: 'male'}
    ];
})

2 个答案:

答案 0 :(得分:1)

您可以使用ng-showng-if

执行此操作
  <span ng-show="test.gender == 'female'">
    <p ng-show="test.pick == 'she'">{{ test.pick }} is a girl</p>
    <p ng-show="test.pick == 'her'">{{ test.pick }} hair is pretty</p>
  </span>
  <p ng-show="test.gender == 'male' && test.pick == 'he'">{{ test.pick }} is a boy</p>

映射对象可以将其清理一下:

$scope.type = {'she': 'girl', 'he': 'boy' };
...
<p ng-if="type[test.pick]">{{test.pick}} is a {{type[test.pick]}}</p>

答案 1 :(得分:0)

此示例与j.wittwer的方法没有什么不同,但我使用了包含所有相关数据的单个对象,然后使用Underscore查找并过滤来自该源的数据。

听起来你在构思一个解决方案时遇到了困难,所以我认为在我们认为你想要达到的目标上看到一些方法可能会有所帮助。

JS (来自控制人员)

$scope.sentenceComponents = [
  { pronoun: 'she', gender: 'girl', sentenceType: 1},
  { pronoun: 'her', gender: 'girl', sentenceType: 2},
  { pronoun: 'he', gender: 'boy', sentenceType: 1},
  { pronoun: 'him', gender: 'boy', sentenceType: 2}
];

$scope.genders = _.uniq(_.pluck($scope.sentenceComponents, 'gender'));
$scope.sentenceTypes = _.uniq(_.pluck($scope.sentenceComponents, 'sentenceType'));

$scope.selectChange = function() {
  $scope.selectedComponents = _.findWhere($scope.sentenceComponents, {gender: $scope.selectedGender, sentenceType: $scope.selectedType});
};

$scope.selectedGender = 'girl';
$scope.selectedType = 1;
$scope.selectChange();

<强> HTML

<select ng-model="selectedGender" ng-options="gender for gender in genders" ng-change="selectChange()"></select>
<select ng-model="selectedType" ng-options="sentenceType for sentenceType in sentenceTypes" ng-change="selectChange()"></select>

<p ng-show="selectedComponents.sentenceType == 1">
  {{ selectedComponents.pronoun }} is a {{ selectedComponents.gender }}
</p>
<p ng-show="selectedComponents.sentenceType == 2">
  The {{ selectedComponents.gender }} took the books from {{selectedComponents.pronoun}}
</p>

Plunker Demo