簡體   English   中英

角度指令

[英]Directives in Angular

我的代碼中有此指令視圖:

<div class="busy-indicator angular-animate" ng-show="busy"></div>
<div class="breadcrumblist" ng-class="atTopLevel ? ['at-top-level'] : null">
    <div class="breadcrumblist-display angular-animate">
        <label id="searchBox">Search</label><input class="c-context-menu-container  t-menu-background  c-context-menu-text" type="text" autocomplete="off" id="IdSearch" ng-model = "searchText.Name">
        <div class="breadcrumblist-parents">
            <div ng-show="::parents && parents.length >= 1"
                 ng-repeat="parentLink in parents"
                 class="breadcrumblist-parent-link t-breadcrumb--parent-bgcolor t-border--bottom-grey48"
                 ng-click="navUpToParent(parentLink)"
                 ng-class="{'selected': isSelected(parentLink.object), 'draggable': isDraggable(parentLink.object)}"
                 data-index="{{$index}}">


        </div>

但是,searchBox出現在我的應用程序的所有位置,但是我想使其僅出現在一個指令上。 我該怎么辦? 我努力使范圍變量僅帶有條件的“ ng-show”這個特定的搜索框,但我不知道該怎么做,你能幫我嗎?

在為您的特定問題提供更多信息之前,您可以執行以下一些可能相關的操作來調試問題並找到解決方案

searchBox出現在我應用程序的所有位置,但我想使其僅出現在一個指令上

指令名稱及其限制的組合可能會導致指令出現​​在不需要的位置。

有關restrict更多信息(如果需要)

因此,例如,如果您有一個名為“ breadcrumblistParentLink”的指令(僅限於C (類)),則可能會在不希望的位置找到它,因為您還使用此類來設置頁面上某些元素的樣式。

如果是這種情況,您可能會發現將指令限制為屬性和元素並提供一些唯一名稱很有幫助。

我也想參考你的問題

只是用條件“ ng-show”這個特定的搜索框,但是我不知道該怎么做

如果您想要某個指令實例的特定行為,可以通過多種方法來實現。

最常見的是傳遞屬性。 例如,這就是您的使用方式

  <div my-awesome-directive show-searchbox="true"></div>

這就是將show放在指令范圍內的方式

angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox">This is search box</span>',
    restrict: 'A',
    scope: {
      showSearchBox: '<'
    },
    link: function(scope, element, attrs){
      console.log(scope.showSearchBox);
    }
  }
})

您可以在這里試用: https : //plnkr.co/edit/4MdNeEafbZjq2kEFKYAl?p=preview

您還可以在attrs變量( attrs.showSearchBox )上查看指令,並在某些情況下attrs.showSearchBox綁定。

例如:

angular.module('myApp',[]);

angular.module('myApp').directive('myAwesomeDirective', function(){
  return {
    template: 'this is my template <span ng-show="showSearchBox()">This is search box</span>',
    restrict: 'A',
    scope: {

    },
    link: function(scope, element, attrs){
      scope.showSearchBox = function(){
       return attrs.showSearchBox; 
      }
    }
  }
})

注意我在示波器上使用了一個函數。

如果您更喜歡jquery,則此函數還可以引用DOM並執行類似$(element).is('[show-search-box]') -但強烈建議您堅持使用角度做事。

暫無
暫無

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

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