2014-04-21 39 views
0

嗨我想讓我的頭繞過這些指令。將值傳遞給指令並更改css屬性

基本問題: 我在我的作用域中有一個名爲箭頭的屬性,它保存圖像(箭頭)應通過css(transform:rotate)旋轉的角度。我有建立一個指令,它應該做的工作:

HTML:

<div class="weather-div"> 
    <img ng-src="../img/icons/wetter/wind-arrows/direction.png" 
     arrowdirection="{{ menu.weather.arrow }}"> 
</div> 

指令:

AppDirectives.directive("arrowdirection", [function(){ 

     return { 
     template: '', 
     restrict: 'A', 
     scope: { }, 
     link: function(scope, element, attrs) { 

      // get the angle from the parent scope 
      var angle = scope.arrow; 

      // get the image to turn() 
      var element = angular.element(document).find('#theimagetofindfromsameobjectdirectiveisin'); 

      // turn img 
      element.css({ 
       '-moz-transform': 'rotate('+angle+'deg)', 
       '-webkit-transform': 'rotate('+angle+'deg)', 
       '-o-transform': 'rotate('+angle+'deg)', 
       '-ms-transform': 'rotate('+angle+'deg)' 
      }); 




     } 
    }; 

}]); 

1:我如何訪問父範圍值menu.weather.arrow在指令或將值傳遞給指令並在那裏訪問? 2:如何獲取圖像元素?

回答

3

我討厭編寫盲目的指令(當你無法測試時有太多的錯誤空間)。如果你製作一個小提琴/ plnkr我可以更新。

重點拿走的題:

  1. 你不需要使用ng-src,除非你是有約束力的東西,會改變。
  2. scope: {}將您從父控制器中分離出來。您需要使用scope屬性將箭頭方向鏈接到作用域上的箭頭(arrow='=arrowDirection)。這將建立一個雙向數據綁定到您在調用指令時設置的值。
  3. 在指令中使用範圍時,如果您需要駱駝案例,請在單詞之間加上-
  4. arrow將不會被設置爲指令鏈接,因此您需要設置手錶。
  5. 通過angular可以訪問element指令附加到您不需要查詢的指令。
  6. 需要更多的時間問你一個問題,你更容易得到響應,如果你A.格式的代碼,B.創建一個簡單的例子,用小提琴/ plnkr

<div class="weather-div"> 
    <img src="../img/icons/wetter/wind-arrows/direction.png" 
     arrow-direction=" menu.weather.arrow"> 
</div> 

//Javascript 
AppDirectives.directive("arrowdirection", [function(){ 
    return { 
    template: '', 
    restrict: 'A', 
    scope: { 
     arrow :'=arrowDirection' 
    }, 
    link: function(scope, element, attrs) { 

     // get the angle from the parent scope 
     var angle = scope.arrow; 
     scope.$watch('arrow', function(){ 
      // get the image to turn() 
      // element is the img 
      element.css({ 
      '-moz-transform': 'rotate('+angle+'deg)', 
      '-webkit-transform': 'rotate('+angle+'deg)', 
      '-o-transform': 'rotate('+angle+'deg)', 
      '-ms-transform': 'rotate('+angle+'deg)' 
      }); 
     }); 

    } 
    }; 
}]); 
+0

謝謝你的回答。我可以成功獲得價值。謝謝!!!!! – Tino