2017-09-28 26 views
1

我想通過一個可選參數isvalid從我的HTML到指令。我遵循文檔中提到的所有步驟,但它仍然看起來像我做錯了什麼..我無法讀取我的指令中的值。你能讓我知道我做錯了什麼嗎?Angularjs - 通過指令的可選參數從HTML

HTML

<customvideo isvalid="true"></div> 

MY指令
更新:我已經簡化了質疑的目的,因此你看到$範圍。我已經更新了實際的指令現在

// Set the directive 
    angular 
     .module('custom.directives') 
     .directive('customvideo', customvideoDirective); 

    // Set the directive $injections 
    customvideoDirective.$inject = ['$Scope']; 


function customvideoDirective($Scope) 
{ 
      return { 
       compile: compile, 
       restrict: 'A', 
       $Scope: { 
        isvalid: '=?' 
       } 
      }; 

    function compile() { 
     console.log($Scope.isvalid); //this is undefined 
    } 
    } 

})(); 
+0

'$ Scope'應該是'作用域' –

+0

thankyou @PankajParkar。我把它注入$ scope。我刪除它這裏簡單...它是這樣的://設置指令 角 \t \t .module( 'custom.directives') \t \t .directive( 'customvideo',customvideoDirective); //設置指令$注入 customvideoDirective。$ inject = [ \t \t'$ Scope' ]; –

+0

請檢查我的答案如下.. –

回答

1

更改你的內心Directive Definition Object(DDO)$Scope屬性應該改變scope。同樣使用link函數而不是使用compile,因爲compile函數只能訪問原始DOM,所以其中沒有可用的範圍。即使你可以從編譯函數返回並且PreLink/PostLink,但在這種情況下,我相信使用link將是適當的。

angular.module('directives') 
.directive('customvideo', function() { 
    return { 
     link: link, 
     restrict: 'A', 
     scope: { 
      isvalid: '=?' 
     } 
    } 
); 

function link(scope) { 
    console.log(scope.isvalid); 
} 
0

找到一種方法來解決它..不知道這是否是最好的..但嘿..它工作:)在這裏張貼對於那些誰到這裏來尋找答案...... 我在寫編譯錯誤的語法...我將它改爲

function compile(tElement, tAttrs, transclude) 
    { 
    // the tAttrs param has all the attributes associated with the element 
    console.log(tAttrs.isvalid); 
    } 
+0

這是不正確的做法。編譯函數不正確的位置查找傳遞給指令的值。請按照上面的答案.. –

+0

謝謝Pankaj ..會介意解釋爲什麼不編譯VS鏈接在我的情況..我不想修改我的DOM或任何東西..我只是想讀取價值..我認爲鏈接應該當我真的想要修改Dom時使用。這會是一個錯誤的假設嗎? –