javascript
  • angularjs
  • angular-directive
  • 2014-10-05 57 views 0 likes 
    0

    本質上我想能夠訪問我創建的指令的父範圍,但我也希望能夠訪問已放置到元素上的屬性。如何從自定義指令中訪問元素屬性,同時保持對父範圍的訪問?

    例如有關JS

    app.directive('testDirective', function(){ 
        return { 
         restrict:"E", 
         templateUrl:"directive.html", 
         scope:{ 
          testAttribute: '=' 
         } 
        }; 
    }); 
    
    app.controller('mainCtrl', function($scope){ 
        $scope.name = 'henry' 
    } 
    

    的index.html

    <div ng-controller="mainCtrl"> 
        <test-directive test-attribute="Hello"></test-directive> 
    </div> 
    

    directive.html

    {{testAttribute}} 
    {{name}} 
    

    輸出爲 「你好」,而不是 「你好亨利」

    所以只是爲了clar rify,我希望能夠做的就是訪問屬性和父範圍。

    +0

    在您的directive.html中,您可以使用'{{$ parent.name}}'來訪問屬性'name'。但是它不合適,因爲它不會促進可重用性。 – ryeballar 2014-10-05 02:37:07

    回答

    1

    對於您正在嘗試做的事情,不需要雙向綁定。您正在嘗試訪問分配爲屬性的文本。你可以只寫你的指令爲: - 的指令設置

    .directive('testDirective', function(){ 
        return { 
         restrict:"E", 
         //scope:true, //apply if required 
         templateUrl:"directive.html", 
         link:function(scope, elm, attrs){ 
          scope.testAttribute = attrs.testAttribute; //Get it from attributes 
         } 
        }; 
    }); 
    

    Demo

    現在這裏scope屬性是要使用父範圍本身。但是,您可能想要使用scope:true(父級子範圍)或2 way binding機會隔離範圍的理想方案。但在這一點上,由於不確定你最初的目標是什麼,這是一個基於你的問題的解決方案。

    所以總結: -

    我希望能夠訪問我創建

    取下隔離範圍,只是使用父母的範圍指令的父範圍。

    但我也希望能夠訪問我已放置到元素上的屬性。

    使用attrs鏈接函數的參數(attrs.testAttribute)。如果你想評估它作爲綁定值do(scope.$eval(attrs.testAttribute)

    +0

    嘿感謝徹底的解釋,它運作良好,但是當你有一個以上的指令,它似乎採取了最後一個指令的屬性,並將其應用於所有的指令。 [示例](http://plnkr.co/edit/XPilCbNtBJ5HgvSUrLe3?p=preview) – Joel 2014-10-05 05:32:45

    +0

    像這樣.. http://plnkr.co/edit/IGc3tK?p=preview。最後一行在我的答案。您也可以使用雙向綁定(如果需要)。 – PSL 2014-10-05 05:37:14

    +0

    太棒了,非常感謝。 – Joel 2014-10-05 06:13:00

     相關問題

    • 暫無相關問題^_^