1

So I understand that $parse creates a function from a string, like $parse('name') will return the name property from a given object. My question is if it can somehow also return the type of said property, something like:

var getType = $parse('typeof name');
var test = getType({name: 'Name1'}); //should be 'string'
1

2 Answers 2

1

The $parse service does not evaluate the JavaScript typeof operator. If you wish to use typeof in an AngularJS expression, create a typeof function and add it to scope.

angular.module("app",[])
.run(function($parse) {
    var getType = $parse("typeof(name)");
    var typeofFn = x => typeof x;
    var test = getType({name: "Name1", typeof: typeofFn});
    console.log(test); //prints "string"
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
</body>

For the limitations of expressions that can be parsed read AngularJS Developer Guide - AngularJS Expressions vs. JavaScript Expressions.

If you want to run more complex JavaScript code, you should make it a controller method and call the method from your view.

Sign up to request clarification or add additional context in comments.

Comments

1

Check this example $pase give you a setter/getter option.

And then use typeof(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) to know what type is the value the getter is using.

Using the getter you get a string in this case.

var Controller = function($parse) {
  var vm = this
  var getter = $parse('user.name')
  var setter = getter.assign
  var context = {
    user: {
      name: 'AngularJS'
    }
  };
  
  setter(context, 'newValue')
  var test = getter(context)
  
  if (typeof test == "boolean") {
    console.log("boolean logic")
  } else if (typeof test == "string") {
    console.log("string logic")
  } else if (typeof test == "number") {
    console.log("number logic")
  } else if (typeof test == "undefined") {
    console.log("undefined logic")
  }
  
  // IT is a string
  vm.test = "typeof= " + typeof test

};
Controller.$inject = ['$parse']

angular
  .module('app', [])
  .controller('Controller', Controller);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Controller as vm">
  {{vm.test}}
</div>

2 Comments

I'm asking if I can get the type within the $parse function. I realize I can get it from the result of the function, but that doesn't help me, my string to parse is more complex and i need to do different operations inside it based on the property type.
Check now the example you can add your logic for any case you want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.