Calling directive's methods from parent controller in AngularJS

后端 未结 5 1113
无人及你
无人及你 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:28

    You can achieve calling directive methods without relying on $broadcast or removing scope isolation. Similar approaches that have been posted here so far will break if there are 2+ instances of the directive on a page (they'll all reflect the same changes).

    This codepen demonstrates a more robust way to do it.

    angular.module('myApp', [])
    .controller('myChat', function($scope) {
        
        function room () {return { accessor:{} }; }
        $scope.rooms = { 'RoomA': new room, 'RoomB': new room, 'RoomC': new room };
    
        $scope.addMessageTo = function(roomId, msg) {
          if ($scope.rooms[roomId].accessor.setMessage)
            $scope.rooms[roomId].accessor.setMessage(msg);
        };
    
        $scope.addMessages = function () {
          $scope.addMessageTo("RoomA", "A message");
          $scope.addMessageTo("RoomB", "Two messages");
          $scope.addMessageTo("RoomC", "More messages");
        }
        
    }).directive('myChatRoom', function() {
    
        return {
          template: '
    {{room}} message = {{message}}
    ', scope: { accessor: "=", room: "@" }, link: function (scope) { if (scope.accessor) { scope.accessor.setMessage = function(msg) { scope.message = msg; }; } } }; });
    
    

提交回复
热议问题