Search code examples
javascriptangularjsangularjs-1.5angular-component-router

Angular JS 1.5 - I want to communicate between angular js components


I am trying to expose deletePhoto and editPhoto methods of businessPhotos components into verticalGrid component. But some how it is not accessible.

Any help would be appreciated, thanks

photo.js

angular.module('business')
  .component('businessPhotos', {
    templateUrl: 'business/photos.html',
    controller: [ function() {
      var $ctrl = this;
      $ctrl.editPhoto = function(photo) {
       // code
      };

      $ctrl.deletePhoto = function(id) {
       // code
      };
    }]
  });

photo.html

<vertical-grid ng-if="$ctrl.business.provider_photos" cells="$ctrl.business.provider_photos" delete-photo="$ctrl.deletePhoto(id)" edit-photo="$ctrl.editPhoto(photo)"></vertical-grid>

vertical-grid.js

angular.module('dashboard')
  .component('verticalGrid', {
    bindings: {
      cells: '<',
      deletePhoto: '&',
      editPhoto: '&'
    },
    templateUrl: 'utils/vertical-grid.html',
    selector: 'vertical-grid',
    controller: ['$element', function($element) {

      var $ctrl = this;

      $ctrl.colGrid = [];
      var numOfCols = 4;
      var numOfCells = $ctrl.cells.length;

      $ctrl.colCssClass = 'col-xs-3';


      for (var i = 0; i < numOfCells; i++) {
        var colIndex = i % numOfCols;
        if (!$ctrl.colGrid[colIndex]) {
          $ctrl.colGrid[colIndex] = [];
        }
        $ctrl.colGrid[colIndex].push($ctrl.cells[i]);
      }
    }]
  });

vertical-grid.html

<div class="provider-photos row">
  <div class="{{$ctrl.colCssClass}}" ng-repeat="col in $ctrl.colGrid track by $index">
    <div class="photo-outer-tile" ng-repeat="cell in col track by $index">
      <div class="photo-tile">
        <img ng-src="{{cell.tile_url}}">
        <div class="photo-controls">
          <a ng-click="$ctrl.deletePhoto(cell.id)" href="javascript:void(0);">Delete</a>
          <a  href="javascript:void(0);">Crop</a>
        </div>
      </div>
    </div>
  </div>
</div>

Solution

  • To communicate between angularjs controllers you could use a service (or a factory, which is conceptually very similar).
    See for example here.
    You can propagate events in real-time from a service to controllers using the $watch concept.

    A simpler way is to use inject $rootScope in both controllers.