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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With