在AngularJS中,为什么布尔参数被评估为字符串?

时间:2013-07-02 10:59:59

标签: angularjs angularjs-directive

在AngularJS中,我想在指令中测试一个布尔值,但该值以字符串形式返回。

以下是代码:

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

如果在指令中有一个“boolean”类型,我该怎么办?

1 个答案:

答案 0 :(得分:10)

使用$ watch,它将根据范围评估观察到的属性表达式:

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

或使用范围。$ eval:

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

DEMO PLUNKER