Tuan-Anh Tran

AngularJS diary - Day 4

Posted on January 9, 2015  •  2 minutes  • 243 words

##Update ng-model of one controller from another

Using $broadcast to broadcast a message (or $emit) and put listener on that message on receiver.

// unrelated controllers -> $rootScope broadcasts
App.controller('Ctrl1', function($rootScope, $scope) {
  $rootScope.$broadcast('msgid', msg);

App.controller('Ctrl2', function($scope) {
  $scope.$on('msgid', function(event, msg) {

When to use $broadcast and when to use $emit?

In case there is no parent-child relation, use $rootScope to $broadcast.

##Making AJAX call the right way

Use service, factory or providers for that. It’s advised not to make AJAX calls within the controller.

var ExampleService = angular.module("ExampleService", []);
ExampleService.service('ExampleService', function($http) {
  this.my_method = function() {
    var url = 'http://...';
    var req_params = {};
    return $http.post(url, req_params); // a promise

// using it
ExampleService.my_method().then(function(result) {
  $scope.my_var = result.data;

##Services vs Factory

In most cases, both can be used interchangably.

When you’re using service, Angular instantiates it behind the scenes with the new keyword. Because of that, you’ll add properties to this and the service will return this. When you pass the service into your controller, those properties on this will now be available on that controller through your service. This is why service is most suitable for generic utilities.

factory is useful for for cases like when you don’t want to expose private fields but via public methods instead. Just like a regular class object.

Follow me

Here's where I hang out in social media