Gabriel Tortomano
Gabriel Tortomano

Reputation: 115

AngularJS creating multiple instances of controller

I'm kind of new in Angular and I'm trying to make a simple app using the Routing module with a Parent controller and everything else being a child of that controller. The Problem is that each time the Parent Controller calls a view, a new instance of that child controller is created, which means my functions get called multiple times. I'm pretty sure I'm doing something wrong, not sure what it is...

here's part of my app.js

var module = angular.module('stock', ['ngRoute', 'ngAnimate']);

module.config(function($routeProvider) {

$routeProvider
    .when('/Dashboard/', {
        templateUrl: '/Dashboard',
        controller: 'DashboardCtrl'
    })
    .when('/Proveedores/', {
        templateUrl: '/Proveedores',
        controller: 'ProveedoresCtrl'
    })
    .when('/DatosArticulo/', {
        templateUrl: '/DatosArticulo',
        controller: 'DatosArticuloCtrl'
    })

.when('/IngresarArticulo/', {
    templateUrl: '/IngresarArticulo',
    controller: 'IngresarArticuloCtrl'
})

.otherwise({
    redirectTo: '/Dashboard'
});
});

part of index.html

<body ng-app="stock" ng-controller="MainCtrl" ng-init="init()" ng-cloak>
    <div class="dropdown-content">
                <a href="#!/IngresarArticulo">
                    <i style="font-size:22px;margin-right:8px" class="fa fa-plus-circle" aria-hidden="true"></i> Ingresar Articulo
                </a>
                <a href="#!/Proveedores">
                    <i style="font-size:22px;margin-right:8px" class="fa fa-product-hunt" aria-hidden="true"></i> Proveedores
                </a>
                <a href="#!/DatosArticulo">
                    <i style="font-size:22px;margin-right:8px" class="fa fa-info-circle" aria-hidden="true"></i> Datos Articulo
                </a>
            </div>

  <div style="z-index:50" id="mainContent" class="view-animate-container">
    <div ng-view class="view-animate"></div>
  </div>
  
  <script type='text/ng-template' id='/Dashboard'>
    <!-- Magic from this view-->
  </script>
  <script type='text/ng-template' id='/Proveedores'>
     <!-- Magic from this view-->
  </script>

EDIT

The Problem (to be more clear) is that I'm broadcasting an event from the Main controller to one of the children's controller, what the controller does once the event is listened is inserting data to my DB, and since there are multiple instances of that controller, the data gets inserted multiple times, how can I avoid that?

Upvotes: 0

Views: 55

Answers (0)

Related Questions