Calling directive's methods from parent controller in AngularJS

后端 未结 5 1111
无人及你
无人及你 2021-02-03 22:59

I am using AngularJS with the alias controllers pattern. I can\'t access (or I don\'t know how to) directive methods from a parent controller.

I have a

5条回答
  •  情歌与酒
    2021-02-03 23:23

    After trying both the $broadcastand the control object solutions, I would actually recommend trying to bind values or arrays. The control object is a simple way to achieve the desired result, but in my testing very undiscoverable and error-prone.

    This Codepen builds BernardV's example, but uses an array of messages as a very visible control binding. If you want, you can easily $watch the messages array inside the directive as well. The core idea is to in the directive use:

    scope: { messages: "=", room: "@" },
    

    From a controller (having an array of "rooms") you would do this:

    $scope.addMessages = function () {
      angular.forEach($scope.rooms, function(room, index) {
        room.messages.push("A new message! # " + (index+1);
      })
    } 
    

    Independent directives, independent messages and highly discoverable. You could of course in the directive only show the latest message, or simply bind a string instead of an array. This solution worked much better for us at least.

提交回复
热议问题