10

In AngularJS I would like to test a boolean value inside a directive, but the value is returned as a string.

Here is the code:

angular.module('TestApp', ['TestApp.services', 'TestApp.controllers', 'TestApp.directives']);

angular.module('TestApp.services', ['ngResource']).
  factory('Obj', function($resource){
        return $resource('datas.json');
    });

angular.module('TestApp.controllers', []).
    controller('TestCtrl', ['$scope', 'Obj', function($scope, Obj) {
        $scope.objs = Obj.query();
    }]);

angular.module('TestApp.directives', []).
  directive('requiredStatus', function() {
        return function(scope, elm, attrs) {
            attrs.$observe('v', function(av) {
                if (attrs.completed) {
              scope.val= true;
                } else {
                    scope.val= false;
                }
            scope.type = typeof attrs.completed;
            });
        };
    });

http://plnkr.co/edit/DvIvySFRCYaz4SddEvJk

What should I do to have a typeof "boolean" inside the directive?

JJJ
  • 32,902
  • 20
  • 89
  • 102
François Romain
  • 13,617
  • 17
  • 89
  • 123
  • 2
    Interpolated attribute values are are always strings see this answer http://stackoverflow.com/a/12372494/527968 – Liviu T. Jul 02 '13 at 11:30

1 Answers1

10

Use $watch, which will evaluate the observed attribute expression against the scope:

scope.$watch(attrs.completed, function(completed) {
  scope.val = completed;
  scope.type = typeof completed;
});

or use scope.$eval:

scope.val = scope.$eval(attrs.completed);
scope.type = typeof scope.val;

DEMO PLUNKER

Stewie
  • 60,366
  • 20
  • 146
  • 113
  • thank you ! in my production code, when i use `scope.$watch`, it returns an error : `TypeError: Cannot read property 'exp' of undefined`. when i use `scope.$eval(attrs.completed)`, it's `undefined`. The last solution is working when i put it inside the `$observe` pattern. Finally i did this, but i don't really understand what's happening and why it is working… – François Romain Jul 02 '13 at 13:11
  • Well, the SO link from @liviut comment does a great job of explaining this behaviour. – Stewie Jul 02 '13 at 13:14