0

I am new to Angular js.I have seen the similar question, but I dont understand that. I have 2 controllers

userControllers.controller('RatingCtrl', function($scope,$http,$rootScope,$route)
userControllers.controller('otherProfileCtrl', function ($scope, $routeParams, $rootScope, $http, $location, $window, $timeout,$uibModal, $compile) 

RatingCtrl and otherProfileCtrl, this two modules are inter-related. My need is that, I have reload RatingCtrl from otherProfileCtrl using $route.reload();.Is there is any way to do this without uisng service?plz help

2
  • why don't you want to use a service? Commented Jun 10, 2016 at 5:35
  • I think it is difficult.If it is only possible by service, I can try on that way Commented Jun 10, 2016 at 5:37

1 Answer 1

4

You could pass events from one controller to another in order to achieve this. You would then do something like:

var app = angular.module('myApp', []);

app.controller('firstController', ['$scope', '$rootScope',
  function($scope, $rootScope) {

    $scope.text = 'Initial text';
    $scope.changeText = function(message) {
      $scope.text = message;
    };

    $rootScope.$on('customEvent', function(event, message) {
      $scope.changeText(message);
    });

  }
]);

app.controller('secondController', ['$scope',
  function($scope) {

    $scope.message = 'Message from second controller';

    $scope.sendEvent = function() {
      $scope.$emit('customEvent', $scope.message)
    };

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="firstController">
    <h2>This is the fist controller:</h2>
    <p>{{text}}</p>
  </div>
  <div ng-controller="secondController">
    <h2>This is the second controller:</h2>
    <input type="text" ng-model="message" />
    <br>
    <button ng-click="sendEvent()">Send message</button>
  </div>

</div>

Here, the firstController listens to events propagated to the $rootScope, and the secondController sends the message. That is the functionality that you are looking for.

That being said, you would be much better off implementing shared behaviour in a service, since keeping track of all your custom events can be particularly tough.

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

if we are trying to do same thing but in two different apps... what change would we require? means I've 2 controllers in 2 different apps (in same project)
@NullPointer assuming that you are using Angular 1.*, I can't think of a way to do this properly between two completely independent modules. That being said, if there is a hierarchy between your modules (e.g. one depends on another), the same solution should apply, since there is only one root scope. Though, I'm pretty rusty on my angular.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.