jhummel
jhummel

Reputation: 1764

Changing parent controller property from child state in uiRouter

I'm refactoring an Angular 1.5 application and I'm trying to work through a problem without taking apart the entire application.

My problem is this; I have a parent state controller with a property. A child state template contains a component that needs to update the property in the parent state.

My states are set up like so:

$stateProvider
  .state('parent', {
    abstract: true,
    component: 'parentComponent'
  })
  .state('parent.child', {
    url: '/child',
    component: 'childComponent'
  })

The child component has a template containing it's own component that specifies a controller method as a callback:

 <grand-child on-change="$ctrl.doSomething()"></grand-child>

I want that callback to change a property on the parent controller.

I could do something like inject $scope in the parent controller, then add the property to the scope object and use scope inheritance to change the property from the child, but I'm trying to remove $scope from the project, not add more of it. Is there any other way I can update the parent controller?

Upvotes: 3

Views: 387

Answers (1)

In such a chained senario,

I would recommend you to store the property in a service

(function () {
    'use strict';

    angular
        .module('app')
        .service('MyService', MyService);

    MyService.$inject = [];

    /* @ngInject */
    function MyService() {



        this.myProperty = ''; // some default value if exists
    }
})();

In your grand-child component's controller inject MyService then

doSomething() {

  this.MyService.myProperty = 'some new value';
}

In your parent component's controller inject MyService then

$onInit() {

  this.myProperty = this.MyService.myProperty;
}

Upvotes: 2

Related Questions