【问题标题】:AngularJS ng-switch or similar to work with a dynamic valuesAngularJS ng-switch 或类似的使用动态值
【发布时间】:2016-05-18 13:54:19
【问题描述】:

我的 controller.js 中有一个数组。我需要用户插入输入文本值,如果正确,则显示一件事,如果不同则显示另一件事。我有多个实例,然后我计划使用ng-switch,但不要让我获得变量范围的值。我该如何解决?

INDEX.html

<body ng-app="formAdictos">
    <div ng-controller="MyController">
    <div ng-repeat="list in lista"></div>
    <div ng-switch on="lis">
      <input type="text" ng-model="lis">
      <div ng-switch-when="{{lista[0]}}">S</div>
      <div ng-switch-when={{lista[1]}}>Hola</div>
      <div ng-switch-default>Texto para cuando no es ni A ni B</div>
    </div>
    </div>
</body>

controller.js

function MyController($scope, $http) {
    $scope.items = [];
    $scope.lista = [];

    $http({method : 'GET',url : 'https://api.parse.com/1/classes/cupon', 
     headers: { 'X-Parse-Application-Id':'XXX', 
     'X-Parse-REST-API-Key':'XXX'}})
     .success(function(data, status) {
        for(var i = 0; i < data.results.length; i++){
            cupo = data.results[i].cupon50;
            $scope.lista[i] = cupo;
        }
        console.log($scope.lista);
    })
    .error(function(data, status) {
        alert("Error");
    });
}
angular.module('formAdictos').controller('MyController', MyController);`

列出一个包含三个值的数组。

lista = ["hi","good","bad"] 这是 http 调用的结果

【问题讨论】:

  • 请编辑问题以包含从您的 $http 调用返回的 JSON。
  • $scope.lista = ["hi","good","bad"] 这是结果

标签: javascript html angularjs parse-platform ng-switch


【解决方案1】:

好吧,我并没有真正的 switch 指令,它似乎也不起作用,所以我带来了其他东西。

function MyController($scope, $http) {
    $scope.items = [];
    $scope.lista = [];
   $scope.lis = "";
   $scope.lista = [{key:"hi", value:"S"}, {key:"good", value:"Hola"}] ;
   $scope.isInList = false;
   $scope.checkIsInList = function(lis){
     $scope.isInList = false;
     for(var i =0; i < $scope.lista.length; i++){
         if($scope.lista[i].key === lis){
             $scope.isInList = true;
             return;
         }
     }
   }
}
angular.module('formAdictos', []).controller('MyController', MyController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="formAdictos">
    <div ng-controller="MyController">
       <input type="text" ng-model="lis" ng-change="checkIsInList(lis)">
       <div ng-repeat="item in lista">
          <div ng-if="item.key == lis"><span ng-bind="item.value"></span></div>
    </div>
   <div ng-if="isInList==false">Texto para cuando no es ni A ni B</div>
     lis : {{lis}}
   </div>
 
</div>

按预期工作,我必须使用布尔值来管理默认值。

但是,如您所见,您需要将服务器中的列表与对象列表中的匹配值列表合并,以使其像我一样工作。另一种方法是使用ng-repeat 提供的$index 提供2 个数组,其中匹配项具有相同的索引

【讨论】:

  • 谢谢我的朋友...这与我想要的相似。我可以使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多