编程语言
首页 > 编程语言> > javascript – 带有typeof表达式的ng-switch

javascript – 带有typeof表达式的ng-switch

作者:互联网

所以我有一个可以是任何类型的变量.按类型我的意思是它可以是一个字符串或一个对象.我正在尝试根据类型运行不同的代码.

我的变量名为range,它是在JavaScript中定义的.我试过的是.变量是我正在循环的对象.

<tr ng-repeat="(key, range) in vars">
    <td ng-switch="typeof range">
        <span ng-switch-when="string">It's a string</span>
        <span ng-switch-when="object">It's an object</span>
        <span ng-switch-default>It's something else</span>
    </td>
</tr>

但这会抛出无效的表达式错误.最好的方法是什么?

解决方法:

试试这个……我还为不同类型的变量添加了检测:string,array,object,number,null和undefined.

"use strict";
angular.module('myApp', [])
.controller("myController", function() {
    this.vars = {
        key1: "String",
        key2: "String2",
        key3: 42,
        key4: {
            name: "Mr. Anderson"
        },
        key5: [1, 2, 3, 4, 5],
        key6: null,
        key7: undefined
    };
    this.getTypeOf = function(value) {
        if(value === null) {
            return "null";
        }
        if(Array.isArray(value)) {
            return "array";
        }
        return typeof value; 
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<table ng-app="myApp" ng-controller="myController as ctrl">
    <tr ng-repeat="(key, range) in ctrl.vars">
        <td ng-switch="ctrl.getTypeOf(range)">
            <div ng-switch-when="string">It's a string</div>
            <div ng-switch-when="object">It's an object</div>
            <div ng-switch-when="number">It's a number</div>
            <div ng-switch-when="array">It's an array</div>
            <div ng-switch-when="null">It's null</div>
            <div ng-switch-when="undefined">It's undefined</div>
            <div ng-switch-default>It's something else</div>
        </td>
    </tr>
</table>

标签:html,javascript,angularjs,ng-switch,angularjs-ng-repeat
来源: https://codeday.me/bug/20190829/1762481.html