How to get a type of scope variable in Angular expression? How to get a type of scope variable in Angular expression? angularjs angularjs

How to get a type of scope variable in Angular expression?


i think the best way is to create a custom filter and use it as you wish within you expression, you can check this link that use for get the Object.keys of an object

for your case you can use

angular.module('customfilter', []).filter('typeof', function() {  return function(obj) {    return typeof obj  };});


Just to show Zamboney's answer applied to my sample code:

Controller:

angular.module('customfilter', []).filter('getType', function() {  return function(obj) {    return typeof obj  };});var mymodal = angular.module('mymodal', ['customfilter']);mymodal.controller('MainCtrl', function ($scope) {    $scope.b = false;});

View:

<div ng-controller="MainCtrl" class="container">  <div>    {{ b }}    {{ b | getType }}    <div ng-if="(b | getType) == 'number'">      It's a number    </div>    <div ng-if="(b | getType) == 'boolean'">      It's a boolean    </div>  </div></div>

And fiddle: http://jsfiddle.net/g8Ld80x3/5/


You can't do it and for the good reason: Angular expression parser disallows such sort of things in the templates.

If you really want to be able to do so, I recommend to explicitly set helper methods on the $rootScope so it will be available in all your templates:

mymodal.run(function($rootScope) {    $rootScope.typeOf = function(value) {        return typeof value;    };});

You can even reference Angular own utility methods:

 mymodal.run(function($rootScope) {    ['isArray', 'isDate', 'isDefined', 'isFunction', 'isNumber', 'isObject', 'isString', 'isUndefined'].forEach(function(name) {        $rootScope[name] = angular[name];    });});

and use {{ isArray(arr) }} in templates.