10

在 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

我应该怎么做才能在指令中有一个 typeof “boolean”?

4

1 回答 1

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;

演示柱塞

于 2013-07-02T11:47:39.197 回答