在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”?
使用$watch,它将根据范围评估观察到的属性表达式:
原文链接:https://www.f2er.com/angularjs/140689.htmlscope.$watch(attrs.completed,function(completed) { scope.val = completed; scope.type = typeof completed; });
或使用范围$eval:
scope.val = scope.$eval(attrs.completed); scope.type = typeof scope.val;