DhavalR DhavalR - 6 months ago 24
AngularJS Question

How to update select tag in parent controller on emitting from child controller in AngularJS

I am new to

AngularJS
. In my
parentController
I have added a
div
that contains
select
to get
emloyeeList
from
Database
. And in
childController
, I am creating new
Employee
. After employee created, I want to emit this employee to
parentController
and update
select
tag.

Below is what I tried.

mainApp.
controller(
"childController",
['$scope', 'EmployeeFactory', 'CommonFactory', 'EmployeeFactory',
function ($scope, EmployeeFactory, CommonFactory, EmployeeFactory) {
$scope.CreateEmployee = function (newEmployee) {
var response = EmployeeFactory.CreateEmployee($scope.newEmployee);

response.success(function (successData) {
alert(JSON.stringify(successData));

$scope.GetEmployeeList = function () {
EmployeeFactory.GetEmployeeList().success(function (data) {
alert("empCreated-------emit");
$scope.$emit('getEmployeeAfterCreate --- emit-----', { getEmployeeAfterCreate: data });
}).error(function (data) {
alert("getEmpAfterCreate ---- emit-----" + data);
});
};

$scope.GetEmployeeList();
});
response.error(function (errorData) {
alert('ERROR-----------' + errorData);
});
};

}]);

mainApp.controller("parentController", ['$scope', 'EmployeeFactory', 'CommonFactory', function ($scope, EmployeeFactory, CommonFactory) {

$scope.employees = {};
$scope.$on('getEmployeeAfterCreate', function (event, args) {
alert("getEmployeeFrom Create ----------- " + JSON.stringify(args.getEmployeeAfterCreate));
$scope.employee = args.getEmployeeAfterCreate;

$scope.employees = {
ID: $scope.employee.ID,
FName: $scope.employee.FName,
LName: $scope.employee.LName,
Qualifications: $scope.employee.Qualifications,
Gender: $scope.employee.Gender,
Phone: $scope.employee.Phone,
Email: $scope.employee.Email,
Address: $scope.employee.Address,
Cities: $scope.employee.Cities
};
});

}]);


Here
EmployeeFactory
and
CommonFactory
are having methods to get and add employees.
Thanks...

Answer

In the future it might be easier to just post your actual query rather than the whole block but here's you're issue:

You registering the emitter with the name: getEmployeeAfterCreate --- emit----- and you're listening on getEmployeeAfterCreate. These names need to match otherwise there's really no way to tie the two together.

Simplified example:

var mainApp = angular.module("app", []);

mainApp.
controller(
  "childController",
  function($scope) {
    $scope.emitter = function() {
      $scope.$emit('getEmployeeAfterCreate', {
        getEmployeeAfterCreate: {}
      });
    }
  });

mainApp.controller("parentController", function($scope) {

  $scope.$on('getEmployeeAfterCreate', function(event, args) {
    alert("getEmployeeFrom Create ----------- ");
  });
});

DEMO: http://jsfiddle.net/NfPcH/15304/