gpt4 book ai didi

angularjs - 在 AngularJS 中,为什么 bool 参数被计算为字符串?

转载 作者:行者123 更新时间:2023-12-02 06:27:38 25 4
gpt4 key购买 nike

在 AngularJS 中,我想测试指令内的 bool 值,但该值以字符串形式返回。

代码如下:

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”类型?

最佳答案

使用 $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

关于angularjs - 在 AngularJS 中,为什么 bool 参数被计算为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com