LoginSignup
8

More than 5 years have passed since last update.

AngularJSを1.2系から1.3.0にあげたらrequireした親のコントローラを使っているdirectiveでエラーが出た。

Last updated at Posted at 2014-10-14

コードはこんな

error.coffee
"use strict"

#parent
#controller

angular.module("myApp")
.controller("ParentItemCtrl", ($scope,Child) ->
   #.......  coffeeなので自動で波括弧をつけてくれるが明示的につけておいた ............
  {
    removeChildItem: (childId, index)->
      Child.destroy({childId: childId}, ->
        $scope.parent.children.splice(index, 1)
      )
  }
)

#directive

angular.module("myApp")
.directive("parentItem", ->
  restrict: "EA"
  templateUrl: "templates/parent_item.html"
  controller: "ParentItemCtrl"
  scope:
    parent: "=item"
)

#child directive

angular.module("myApp")
.directive("childItem", ($modal)->
  restrict: "EA"
  templateUrl: "templates/child_item.html"
  require: "^parentItem"
  scope:
    child: "=item"
  link: (scope, element, attrs, parentItemCtrl) ->
    scope.open = ()->
      modalInstance = $modal.open({
        templateUrl: "/remplates/modal_confirm.html"
      })

      modalInstance.result.then(->
        parentItemCtrl.removeChildItem(scope.child.id, scope.$index) 
     # ↑ ここでremoveChildItemがないとエラー
      )
)

controllerの関数で公開したいものだけ(この場合はremoveChildItem)をモジュールパターンを使って返していて、1.2系では動いていたけど、1.3では動かなくなった。
chromeのDeveloper Toolsで確認すると、parentItemCtrlは、1.2系では期待どおりオブジェクトがわたってきていたが、1.3では$get.Constructorとなっていた。

↓1.2
1.2.png

↓1.3
1.3.png

ので、コントローラを以下のように変更した。

parent_item.coffee
angular.module("myApp")
.controller("ParentItemCtrl", ($scope, Child) ->
  #.......
  @removeChildItem = (childId, index)->
    Child.destroy({childId: childId}, ->
      $scope.parent.cildren.splice(index, 1)
    )
)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8