2014-04-06 187 views
1

我想編寫一個指令,根據屬性值「name」更改圖像。顯示圖像,但在「名稱」屬性更改時不更新。AngularJS指令更新DOM

HTML:

<img test name="{{finder.name}}" 

JS:

.directive("test", function() { 
    return { 
     restrict: "A", 
     scope: { 
      name: '@' 
     }, 
     link: function(scope, element, attrs) { 
      scope.$watch("name", function(value) { 
       if (angular.isDefined(value)) 
        var replaceName = value.replace(/[ \/]+/g, "_") 
         .toLowerCase(); 
       var tag = '<img src="/images/banner_' + 
         replaceName + '.jpg" class="img-responsive"/>' 
       element.replaceWith(tag); 
      }) 
     }}} 
    ); 

謝謝!

回答

0

這裏是我做了我的簡單的圖像指令..生成動態圖像源..

link: function(scope, element, attrs) { 

     // this will replace the value of your image source 
     var setImagrSRC = function() { 
      element.attr('src','some source value here..') 
     } 

     // this will observe if there is changes on your name directive 
     // and will trigger the function setImageSRC above 
     attrs.$observe('name',setImageSRC); 

}}} 
0

這是因爲你用新的元素用replaceWith方法覆蓋元素。你的指令將會隨着它被破壞。不要更換元件,只需更換屬性:

link: function(scope, element, attrs){ 
    scope.$watch('name', function(value){ 
     ... 
     var imageUrl = value.replace(...); 
     element.attr('src', imageUrl); 
    }); 
}