簡體   English   中英

AngularJS指令傳遞字符串

[英]AngularJS Directive Passing String

該指令試圖創建一個名為進度條的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
}

});

在您的指令中,您正在使用從全局范圍到指令本地范圍的屬性的雙向綁定。

在此模式下,html中的屬性值被計算為表達式,因此您的指令嘗試將其本地scope.error綁定到將true作為表達式求的結果。

當您測試scope.error == "true" ,您實際上測試的是true == "true"並且在javascript中評估為false

要解決您的問題,您可以:

  • 在調用指令時使用帶引號的字符串:

     <progress-bar progress='1' max='6' error="'true'"></progress-bar> 
  • 或者更改指令中的綁定模式,因為您不需要雙向綁定。 @ variables始終是string類型。

     return { restrict: 'AE', scope: { max: '@max', progress: '@progress', error: '@error' }, link: compileProgressBar } 

您可以在Angular $ compile文檔中找到有關綁定模式的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM