2014-10-06 42 views
0

我正在使用AngularJS指令。這個指令有一些自定義屬性。我將使用該指令是這樣的:綁定指令範圍對HTML的價值

<my-directive show-links="false" /> 

show-links是,我想默認爲true如果開發者沒有明確設置它的屬性。在試圖建立這個指令,我有以下的JavaScript:

.directive('myDirective', function() { 
    return { 
    restrict:'E', 
    transclude: true, 
    scope: { 
     showLinks: '=?' 
    }, 
    templateUrl: '/directives/my-directive.html', 
    controller: function ($scope) { 
     if (angular.isUndefined($scope.showLinks)) { 
     $scope.showLinks = true; 
     console.log('show links? ' + $scope.showLinks); 
     } 
    } 
    }; 
}); 

我的HTML我-directive.html如下所示:

<div><h1>Hello! {{showLinks}}</h1></div> 
<div ng-if="showLinks == true""> 
    <a href='#'>do something</a> 
</div> 

當該指令進行評估,我可以看到在控制檯窗口中「顯示鏈接?真實」。但是,在屏幕上,我看不到「真實」打印在「你好」旁邊。就像HTML在showLinks處於範圍之前得到渲染一樣。我究竟做錯了什麼?

+0

嘗試使用'compile'而不是'link'。它用於不同的階段。 – denisazevedo 2014-10-06 13:24:46

回答

0

我記得分離範圍有問題 - 解決辦法是添加任何東西,這是在隔離範圍對象爲指令HTML代碼本身,就像這樣:

.directive('widgetRecentEntries', function(){ 
     return { 
      restrict: "E", 
      replace: true, 
      scope: { 
       recents: "=recents" 
      }, 
      templateUrl: "ngapp/js/tpl/widget-recent-entries.html" 
     }; 
    }) 

該指令HTML /模板:

<dl class="dl-horizontal flip-in" ng-repeat="item in recents" recents="recents"> 
    <dt> 
    <a href="/{{item.seo_name}}.html"> 
     <img src="{{item.logo_url}}" alt="" width="80"> 
    </a> 
</dt> 
<dd> 
    <p><a href="/{{item.seo_name}}.html">{{item.name}}</a></p> 
</dd> 
</dl> 
+0

如果我不使用範圍:'{showLinks:'=?' }',我得到一個運行時錯誤。 – user70192 2014-10-06 13:48:58

+0

@ user70192嘗試像這樣(您的指令HTML代碼): '

' 另請注意,您在'showLinks == true'之後有兩個閉合雙引號(可能沒有任何影響,但仍然...)AND當與布爾值進行比較時,使用'==='而不是'==' – developer10 2014-10-06 13:52:51

+0

忽略ng-if的語法我認爲true或false會顯示在「Hello!」旁邊。在我上面展示的指令中。但是,沒有什麼是顯示。 – user70192 2014-10-06 13:55:25