2013-10-14 125 views
1

我的指令工作正常,顯示所有趨勢標籤。該指令在$ scope對象中查找trendingTag屬性。所以,我有範圍:真正角度指令,範圍:真,並將屬性添加到範圍

app.directive('ngTrending', function() { 
    return { 
     restrict: 'E' 
     , transclude: true 
     , replace: true 
     , scope: true 
     , templateUrl: '/resources/ngViews/trending.html' 

    }; 
}); 

現在我想基於指令屬性可以根據選項來配置它(如只讀=「真」)。並基於attirbute這樣THT

<ng-trending></ng-trending> 

生成啓用行動的趨勢標籤能夠有條件地更改模板的次要方面。雖然

<ng-trending read-only="true"></ng-trending> 

生成標籤,但禁用了點擊。如何在指令上對範圍進行編碼,以便我仍繼承託管該指令的控制器的範圍,例如

<div ng-controller="fancy"> 
    <ng-trending></ng-trending> 
</div> 

現在就是這種情況(在指令模板的內部,我引用了fancyContrilers $ scope.trendingTags屬性)。但是在指令的模板中,我想引用$ scope中的「只讀」。

它只是在我看來,我正在接近這完全錯誤的,我可能想要通過趨勢標籤以及...我很困惑 - 請幫助理清我!

謝謝。

+1

如果你不想改變你的指令的範圍,我認爲你可以在'link'函數中檢查屬性('attrs.readOnly'會給你一個字符串值)。你可以使用'scope。$ eval(attrs。readOnly)'或'$ parse'來進行單向和雙向綁定。 – jpmorin

+0

@ jpmorin的建議對我很好。這不是要養成的習慣,儘管在某些情況下它可以有效。 –

回答

1

正常的過程是使用隔離範圍在指令中傳遞所需的任何變量(除非您需要多個元素指令)。這將導致更多的可重用和可測試指令,並且更清晰的代碼,因爲指令不會與其周圍環境耦合。

對於你的情況下,如果寫的分離物範圍這樣

scope: { 
    trendingTags: '=', 
    readOnly: '=' 
    // ... 
} 

然後就可以在內部範圍上的外部範圍的表達結合trendingTags,並與readOnly在元件上使用屬性相同。然後

您元素看起來像這樣

<ng-trending trending-tags="trendingTags" read-only="true"></ng-trending> 

有在這裏http://docs.angularjs.org/guide/directive分離範圍的更多信息。

+0

是否有可能也默認readOnly爲假 – akaphenom

+1

如果它沒有在屬性上定義,那麼'scope.readOnly'將是'undefined'。你可以測試這個,如果你喜歡,可以使用默認值。或者,你可以使用'scope.readOnly'本身,當你只需要'falsy'的時候undefined ...或者'!! scope.readOnly'會被強制轉換爲布爾值。 – Andyrooger

1

爲了完整起見,我的工作解決方案包括動作綁定。任何批評都歡迎。謝謝andyrooger:

的指令:

app.directive('ngTrending', function() { 
    return { 
     restrict: 'E' 
     , transclude: true 
     , replace: true 
     , scope: { 
      trendingTags: '=' 
      , displayOnly: '=' 
      , inlineLabel: '=' 
      , filterTo: '&' 
      , isFilteredTo: '&' 
     } 
     , templateUrl: '/resources/ngViews/trending.html' 

    }; 
}); 

模板:

<div style="text-align: center"> 
    <div class="btn-group-xs"> 
     <span ng-show="(!!inlineLabel)" style="color: #81B1D9">Tagged: </span> 
     <button ng-repeat="tag in trendingTags | orderBy:'count':true | limitTo:8" type="button" class="btn btn-default btn-primary" 
       style="text-wrap: normal; margin: 2px;" 
       ng-click="filterTo({filterToTag: tag.tagName})" ng-class="{active: isFilteredTo({filterToTag: tag.tagName}), disabled: (!!inlineLabel)}"><span 
       ng-bind-html-unsafe="tag.tagName"></span> <span class="badge" ng-show="!(!!displayOnly)">{{ tag.count }}</span 
     </button> 
    </div> 
    <button type="button" class="btn btn-xs btn-default" style="width: 150px; text-wrap: normal; margin-top: 3px" 
      ng-click="filterTo({filterToTag: ''})" ng-show="!(!!displayOnly)">Clear 
    </button> 
</div> 

在使用中:

<ng-trending trending-tags="tags" 
        filter-to="filterTo(filterToTag)" 
        is-filtered-to="isFilteredTo(filterToTag)"></ng-trending>