Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's define simple boolean on the scope:

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.b = false;
});

How can I get type of a variable in the expression? typeOf and Object.prototype.Tostring.call don't work.

<div ng-controller="MainCtrl" class="container">
        <div>
          {{ b }}
          {{ typeOf(b) }}
          {{ Object.prototype.toString.call(b) }}
        </div>
</div>

Here's JSFiddle: http://jsfiddle.net/g8Ld80x3/2/

like image 233
Arkadiusz Kałkus Avatar asked Mar 08 '16 08:03

Arkadiusz Kałkus


2 Answers

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
  };
});
like image 56
Zamboney Avatar answered Oct 17 '22 08:10

Zamboney


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/

like image 40
Arkadiusz Kałkus Avatar answered Oct 17 '22 07:10

Arkadiusz Kałkus