如何使用范围生成switch case

时间:2017-08-01 19:56:34

标签: javascript angularjs json

我想用a生成这个案例  $ scope.type [i](来自数据库的json数组),怎么做?

$data = array('api'=>'123344');
curl_setopt_array($curl, array(
    CURLOPT_URL => "http://example.com/api",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>  $data,
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
    ),
));

3 个答案:

答案 0 :(得分:0)

您必须将正确的对象值传递给与您的案例匹配的开关。在下面的示例中,如果您从输入传递电话或鞋子,则会触发开关。

var myApp = angular.module('myApp', []);
    myApp.controller('ctrl', ['$scope', function ($scope) {
    $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];

  $scope.getValuesList = function(index) {
    switch ($scope.type[index].nomcarac){
    
      case $scope.type[index].nomcarac: 
        $scope.valuelist = $scope.type[index].nomcarac +" " + "worked";
        console.log($scope.valuelist);
        break;
      default:
        $scope.valuelist = "Nothing worked";
        break;
    }
  };
  for(var i=0;i<$scope.type.length;i++)
    $scope.getValuesList(i);
   }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
</div>

答案 1 :(得分:0)

$scope变量就像普通的javascript变量一样,您可以使用如下变量访问子级别:

item.valuelist = angular.copy($scope[item.type + 'list']);

如果您担心字符串不正确,可以稍后检查null。

答案 2 :(得分:0)

我希望它能按照您的期望

运作

&#13;
&#13;
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];

    $scope.getValuesList = function(item) {
      switch (item.nomcarac) {
        case item.nomcarac:
          item.valuelist = angular.copy($scope.phonelist);
          break;
        default:
          item.valuelist = [];
          break;
      }
    };
    
    for (var i in $scope.type) {
    	$scope.getValuesList($scope.type[i]);
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl" ng-app="myApp">
</div>
&#13;
&#13;
&#13;