pro*_*rer 62 javascript string parameter-passing angularjs angularjs-directive
该指令试图创建一个名为进度条的HTML元素,用于在页面移动到页面时跟踪进度.我正在尝试将其开发用作:
<progress-bar progress='1' max='6' error="true"></progress-bar>
我只是试图将html中的^^元素中的信息传递给我的指令并处理信息以适当地更改进度条.
这适用于"progress"和"max",它取整数值,但由于某种原因,注释掉的代码会处理"错误"(这是一个字符串)会导致问题.我是angularJS的新手,所以如果这些听起来令人困惑或不清楚,我很抱歉......请问我是否需要详细说明/澄清.提前致谢!
app.directive('progressBar', function(){
var compileProgressBar = function(scope, elem, attrs) {
var append = '<nav class="navbar navbar-fixed-bottom navbar-footer" role="navigation">\
<div class="container">\
<div class="row">';
var i = 1;
while (i <= parseInt(scope.max)) {
if (i <= parseInt(scope.progress)) {
//if (scope.error == "true"){
//...
//}
//else {
append += '<div class="col-xs-1"><div class="circle-filled"><center>'+i+'</center></div></div>'
//}
} else {
append += '<div class="col-xs-1"><div class="circle-hallow"><center>'+i+'</center></div></div>'
}
i++;
}
append += '</div></div></nav>'
elem.append(append);
elem.bind('click', function(){
if (scope.progress > 1) {
history.back();
scope.$apply();
}
});
}
return {
restrict: 'AE',
scope: {
max: '=max',
progress: '=progress'
//error: '=error'
},
link: compileProgressBar
}
Run Code Online (Sandbox Code Playgroud)
});
rlu*_*uta 106
在您的指令中,您正在使用从全局范围到指令本地范围的属性的双向绑定.
在此模式下,html中的属性值被计算为表达式,因此您的指令尝试将其本地scope.error绑定到将true作为表达式求值的结果.
当你测试时scope.error == "true"
,你实际上正在测试,true == "true"
并且在javascript中评估为false.
要解决您的问题,您可以:
在调用指令时使用带引号的字符串:
<progress-bar progress='1' max='6' error="'true'"></progress-bar>
Run Code Online (Sandbox Code Playgroud)或者更改指令中的绑定模式,因为您不需要双向绑定.@ variables始终是string类型.
return {
restrict: 'AE',
scope: {
max: '@max',
progress: '@progress',
error: '@error'
},
link: compileProgressBar
}
Run Code Online (Sandbox Code Playgroud)您可以在Angular $ compile文档中找到有关绑定模式的更多信息