2015-04-27 42 views
1

我有我的看法,這些行:AngularJs:自定義指令的動態模板不是替代屬性值

<html lang="en" ng-app="localjhourlad"> 

.....

<ng-carousel-item 
    title="AngularJS custom directive's title attribute" 
    content="I am a custom attribute, as well!" 
    thumbnail="/img/logo.png"> 
</ng-carousel-item> 

而且我app.js文件:

var ngApp = angular.module("localjhourlad", ['ngRoute']); 

ngApp 
    .config(['$interpolateProvider', 
     function ($interpolateProvider) { 
      $interpolateProvider.startSymbol('[['); 
      $interpolateProvider.endSymbol(']]'); 
    }]); 

//Custom Directives 
ngApp 
    .directive('ngCarouselItem', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      template: '<div class="item">' + 
         '<div style="background-image: url([[thumbnail]])">' + 
         '<div class="carousel-caption">' + 
         '<h3>[[title]]</h3>' + 
         '<p class="hidden-sm hidden-xs">[[content]]</p>' + 
         '</div>' + 
         '</div>' + 
         '</div>' 
     } 
    }); 

一切正常,因爲我看到自定義指令元素被指令的模板替換,只有表達式bindi ngs並沒有被屬性值所取代,因爲:

<div class="item" 
    title="AngularJS custom directive's title attribute" 
    content="I am a custom attribute, as well!"  
    thumbnail="/img/logo.png"> 

    <div style="background-image: url()"> 
     <div class="carousel-caption"> 
     <h3 class="ng-binding"></h3> 
     <p class="hidden-sm hidden-xs ng-binding"></p> 
     </div> 
    </div> 
</div> 

我現在沒有想法。任何幫助將非常感激。

+0

它是否與標準括號{{thumbnail}}一起使用? – Yashvit

+0

本機「{{}}」和自定義「[[]]」都不起作用。完全相同的空白結果。 :( –

回答

0

你不是在指令中,這意味着你使用的是母公司的範圍申報範圍。但在該範圍內,thumbnail/title/content不是範圍上的變量,而是DOM元素上的屬性。

你有2種選擇:

要麼聲明隔離範圍,像這樣:

scope: { 
     thumbnail: "@", 
     title: "@", 
     content: "@" 
} 

然後讓你的HTML,因爲它是,或:

添加那些範圍鏈接功能:

link: function(scope, element, attr) { 
    scope.thumbnail = attr.thumbnail; 
    scope.title = attr.title; 
    scope.content = attr.content; 
} 
+1

看到我的答案,如果你宣佈孤立的範圍,那麼你不需要訪問它們作爲attr.template 他們將直接在示波器上提供 – Yashvit

+0

@Yash這就是爲什麼我說2個選項,要麼/或 –

+1

哎呀..對不起,我的壞.. dint閱讀整個答案 – Yashvit

1

嘗試增加的指令DEFN「範圍」對象

ngApp 
    .directive('ngCarouselItem', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      scope: { 
       thumbnail: "@", 
       title: "@", 
       content: "@" 
      } 
      template: '<div class="item">' + 
         '<div ng-style="background-image: url([[thumbnail]])">' + 
         '<div class="carousel-caption">' + 
         '<h3>[[title]]</h3>' + 
         '<p class="hidden-sm hidden-xs">[[content]]</p>' + 
         '</div>' + 
         '</div>' + 
         '</div>' 
     } 
    }); 
+0

謝謝!它的工作原理。我給你一個最高點,我會接受你的答案,但Omri Ahron有一個更全面的答案。 –

相關問題