カスタムディレクティブでAPIから受け取ったデータを表示する

2014-06-12#angular

APIから受け取ったデータを表示するカスタムディレクティブを作る場合、$watchでscopeのプロパティを監視し再描画を行うといった実装が必要になる。

<div ng-controller="MyController">
  <my-directive data="users"></my-directive>
</div>
window.ngApp.controller "MyController" ["$scope", "User", ($scope, User) ->
  $scope.users = User.query()
]
window.ngApp.directive "myDirective", ->
  restrict: "E"
  link: (scope, elements, attrs) ->
    render = (data) ->
      # 描画処理
    scope.$watch(attrs.data, ((newData, oldData) -> render(newData)), true)