2014-12-30 46 views
1

所以我做了基於我的項目Angularjs得到scope屬性沒有自定義指令使用隔離範圍

我用隔離範圍創建2個指令,一個,另一個不是一個小實驗..

的問題是:

  1. 有沒有辦法讓scope屬性,而無需使用隔離範圍是什麼? 因爲在我的項目,我沒有自定義 指令環境隔離的範圍,也是我需要訪問父範圍

  2. 可以使用angular.element(「#」我操作DOM + scope.id )? 如果不是有沒有辦法做到這一點?

這是未分離的自定義指令

<test-directive item="item" content="item.context"></test-directive> 

這是JS碼

app.directive('testDirective', function() { 
    return { 
    restrict: "EA", 
    scope: false, 
    template:"<div>test directive</div>", 
    link: function(scope, elm, attr) { 
     console.log(attr.item); //I want it like the result gives in line 39 
     console.log(attr.id); //I want it like the result gives in line 41 
     console.log(attr.content); //I want it like the result gives in line 43 
     console.log(scope.name); 
    } 
    } 
}); 

這被分離的一個

<isolated-directive id=item.id item="item" content="item.context"></isolated-directive> 

這是JS代碼

app.directive('isolatedDirective', function() { 
    return { 
    restrict: "EA", 
    scope:{ 
     item:'=item', 
     id:'=id', 
     content:'=content', 
    }, 
    template:"<div>isolated directive</div>", 
    link:function(scope,elm,attr) { 
     console.log(scope.item.id); 
     console.log(scope.id); 
     console.log(scope.content); 
     console.log(scope.name); //I want it like the result gives in line 27 
    } 
    } 
}); 

,這是工作plunkr

任何人關心幫助?

回答

0

您可以使用scope: true,範圍將原型從它插入的位置繼承。但是,如果您只需訪問父範圍,則即使在隔離範圍內,也可始終使用$parent。這不被推薦,但它是可能的。

+0

你能給我一個更新的plunkr工作例子嗎? –

+0

http://jsfiddle.net/wchnsyLw/1/ – unobf

+0

哇顯然沒有使用範圍:真我也可以使用它,謝謝你的答覆.. btw如果我想操縱元素?像使用這個angular.element('#'+ scope.item.id);那可能嗎 ? @unobf –

0

Q1:

app.directive('testDirective', function() { 
    return { 
     restrict: "EA", 
     scope: false, 
     template:"<div>test directive</div>", 
     link: function(scope, elm, attr) { 
      console.log(scope[attr.item]); //I want it like the result gives in line 39 
      console.log(scope[attr.id]); //I want it like the result gives in line 41 
      console.log(scope[attr.content]); //I want it like the result gives in line 43 
      console.log(scope.name); 
     } 
    } 
}); 

Q2:

基本上在鏈接功能的PARM elm是你的指令相關的DOM。如果您真的想在您的DOM屬性中使用scope.item.id,請使用ng-attr來定義您的屬性,如下所示。請注意,angular.element僅用於將DOM包裝到JQuery元素,但不用於DOM查找。

<isolated-directive ng-attr-id="{{item.id}}" item="item" content="item.context"></isolated-directive> 
相關問題