Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AngularJS, why is a boolean parameter evaluated as a string?

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?

like image 780
François Romain Avatar asked Jul 02 '13 10:07

François Romain


1 Answers

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

like image 77
Stewie Avatar answered Oct 27 '22 16:10

Stewie