Daniel Ellison
Daniel Ellison

Reputation: 1347

Angular 1 - Sharing data between parent and child controller - Need advice

Im working on 2 apps that will simply display all active incidents and then all closed incidents. The 2 apps share similar logic when it comes to create, modify, save and delete.

So im trying to figure the best aproach to share the CRUD logic between the 2 applications. I tought maybe it would be best to set a parent - child controller setup like so:

Common_CRUD_file.js:

var Common_Application = .module('Common_Application ',[app, app1, app2, app3])
Parent_controller.controller('Parent_controller'), function ($scope, $http, $filter, $timeout) {

//all my CRUD logic goes in here
$scope.edit = function(data) { //edit logic goes here }
$scope.save = function(data) { //save logic goes here }
$scope.cancel = function(data) { //cancel logic goes here }
$scope.delete = function(data) { //delete logic goes here }

}

Child_Show_closed_incidents.js:

var Common_Application = angular.module('Common_Application');
Child_controller.controller('Child_controller'), function ($scope, $http, $filter, $timeout) {

//All of the app logic goes here    
$scope.get_data = function(data) { //store fetched ajax data in $scope.All_closed_incidents  }

}

Quick excerpt of the HTML file:

<div ng-app="Common_Application" ng-controller="Parent_controller">
<div ng-controller="Child_controller">
<table directive_for_angular_app_here>
  <tr>
    <td></td>
    <td>Description</td>
    <td>Status</td>
  </tr>
  <tr ng-repeat="incident in All_closed_incidents">
    <td><button type="button" ng-click="edit(incident)">Edit</button></td>
    <td>{{incident.Description}}</td>
    <td>{{incident.Status}}</td>
  </tr>  
</div>
</div>

So this setup is able to load my table but the edit function dosent seem to fire at all when I click on the button. No errors in the console either. Seems to ignoring my Parent functions all together when I was expecting it to share all of its scopes. Would anyone have a better aproch to this?

Upvotes: 0

Views: 99

Answers (1)

sauce
sauce

Reputation: 592

I would discard the parent/child setup you have. Turn the parent into a service with functions:

    //all my CRUD logic goes in here
$scope.edit = function(data) { //edit logic goes here }
$scope.save = function(data) { //save logic goes here }
$scope.cancel = function(data) { //cancel logic goes here }
$scope.delete = function(data) { //delete logic goes here }

then inject that service into the child controller and call the functions. Reduces complexity and enhances reusability.

Upvotes: 2

Related Questions