【问题标题】:In AngularJS, why is a boolean parameter evaluated as a string?在 AngularJS 中,为什么将布尔参数评估为字符串?
【发布时间】:2013-06-29 17:10:59
【问题描述】:

在 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"?

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

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

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

或使用 scope.$eval:

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

DEMO PLUNKER

【讨论】:

  • 谢谢!在我的生产代码中,当我使用scope.$watch 时,它返回一个错误:TypeError: Cannot read property 'exp' of undefined。当我使用scope.$eval(attrs.completed) 时,它是undefined。当我把它放在$observe 模式中时,最后一个解决方案正在工作。最后我做到了,但我真的不明白发生了什么以及它为什么起作用……
  • 好吧,@liviut 评论中的 SO 链接很好地解释了这种行为。
猜你喜欢
  • 2013-11-11
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多