Last active
August 29, 2015 14:05
-
-
Save onjiro/0946f3292da08705b60a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('colorsOptionDirective').directive('colorsOption', ['$compile', function($compile) { | |
var colors = ["red", "yellow", "blue"]; | |
compile: function(element, attr) { | |
var optionTemplate = angular.element(document.createElement('option')); | |
for (var i = 0; i < colors.length; i++) { | |
$compile(optionTemplate.clone() | |
.val(colors[i]) | |
.text(colors[i]) | |
.appendTo(element)); | |
} | |
} | |
}]); |
linkじゃなくて、compile時にoptionタグを生成したら、optionディレクティブ側でうまいことやってくれないかと思ったけど、うまくいかない模様。
生成したタグに対してはoptionディレクティブが効かないのか、効くけど処理が次回以降のループにまわってしまうのか...
生成したoptionタグに対してはoptionディレクティブのcompileは実行されないことを確認。
この挙動はng-optionsを利用した場合も同じく。
タグの生成なのでlinkではなくcompileを使ったほうがよいかも。
・・・と思ったけど、$selectControllerに依存してしまうので、link内で処理する必要がありました。
(compile時点では$selectControllerが生成されていない)
linkとcompileの使い分けについて
http://angularjsninja.com/blog/2013/11/22/angularjs-custom-directives/
(optionディレクティブのcompileが実行されないのはcompileの性質によるものでした。)
$compile使えば動的に生成したタグにcompileかけれる模様。
これで、optionタグ直書きの場合と同じ扱いにできるので、データが静的な場合は問題なさそう。
データを動的にする場合、$watchCollectionをかける必要があるので全く同じやり方ではできないので注意必要そう
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ただ、colors の値を操作する必要がある場合は$watchとかいれる必要があるかも。もうちょっと中身ちゃんと調べないと変なこと起きそう。。。
option と ng-model については select ディレクティブに密接に関わっているのでなかなかややこしい...