2013-03-18 99 views
0

如何從$ apply指向相同元素的另一個指令中的指令控制器函數?例如:AngularJs中的另一個指令的呼叫控制器

<myelement hint="myelement.controller.getMe()">hoverMe</myelement> 

app.directive("myelement", function() { 
    return { 
     restrict: "E", 
     controller: function ($scope) { 
      this.getMe = function() { 
       return "me"; 
      }; 
     } 
    } 
}); 

app.directive("hint", function() { 
    return { 
     restrict: "A", 
     controller: function ($rootScope) { 
      this.showHint = function (getMsg) { 
      alert($rootScope.$apply(getMsg)); //what should be written here? 
      } 
     }, 
     link: function (scope, element, attrs, controller) { 
      element.bind("mouseenter", function() { 
       controller.showHint(attrs.hint); 
      }); 
     } 
    } 
}); 

來源:http://plnkr.co/edit/9qth9N?p=preview

回答

0

使用要求(閱讀更多關於它here)。

app.directive("hint", function() { 
    return { 
    restrict: "A", 
    require: ["myelement", "hint"], 
    controller: function ($scope) { 
     this.showHint = function (msg) { 
     alert($scope.$apply(msg)); //what should be written here? 
     } 
    }, 
    link: function (scope, element, attrs, ctrls) { 
     var myElementController = ctrls[0], 
      hintController = ctrls[1]; 

     element.bind("mouseenter", function() { 
      hintController.showHint(myElementController.getMsg()); 
     }); 
    } 
    } 
}); 

UPDATE(約製作提示普遍,見下面的評論)

爲了提示指令普及,比你能使用$範圍,因爲它們之間的媒介。

app.directive("myelement", function() { 
return { 
    restrict: "E", 
    controller: function ($scope) { 
     $scope.getMe = function() { 
      return "me"; 
     }; 
    } 
} 
}); 
<myelement hint="getMe()">hoverMe</myelement> 

唯一的變化是,getMe消息沒有在所述控制器(this.getMe),但在$範圍($scope.getMe)設置好的。

+0

我想過要求,但在我的情況下'提示'應該是一個通用指令,可以適用於任何其他指令,它應該知道的唯一的事情是調用什麼函數來獲得結果 – Nutel 2013-03-18 01:37:31

+0

更新瞭解決問題的答案這個要求。作爲替代方案,您也可以在'myelement'處要求'hint'並公開一個提示API來更改消息。我更喜歡我在答案中提出的方式。 – 2013-03-18 01:46:23

+0

只是一個快速修復,你不應該在提示指令中使用'$ rootScope',它應該是'$ scope'。 – 2013-03-18 11:06:42