Home > Enterprise >  AngularJS calling an ng-controller embedded inside another controller
AngularJS calling an ng-controller embedded inside another controller

Time:10-29

Here is a snippet of the cshtml:

<div>
    <button type="button" ng-click="recalcButton()">Recalc Button</button>
</div>
<div ng-controller="appealPartialController">
    <div ng-include="'/Partials/appealsPartial.html'"></div>
</div>

When recalcButton is clicked, I want to reload the data in appealPartialController. Any documentation or JS code examples would be greatly appreciated!

CodePudding user response:

So, after much googling and a good idea fairy, I found a solution utilizing the built in $scope of angularJS and calling the load function from the parent.

$scope.$$childHead.$$nextSibling.loadAppealModel($scope.claimID);

CodePudding user response:

You can use a shared param. First of all you create a service like this:

import { Injectable, EventEmitter } from '@angular/core';
import { Subscription } from 'rxjs/internal/Subscription';

@Injectable({
  providedIn: 'root'
})
export class SharedParamsService {

  invokeFirstComponentFunction = new EventEmitter();
  subsVar: Subscription;

  constructor() { }

  onUpdateEnv(key, val) {
    var toEmit = [key, val]
    this.invokeFirstComponentFunction.emit(toEmit);
  }
}

Now you can emit a variable when clicking your button, so in your component, after importing SharedParamsService and declaring in your constructor private sharedParams: SharedParamsService:

recalcButton(){
    this.sharedParams.onUpdateEnv("btn", this.jobObj.name);
}

Finally, in the component you want to reload after importing SharedParamsService and declaring in your constructor private sharedParams: SharedParamsService:

 this.sharedParams.subsVar = this.sharedParams.
     invokeFirstComponentFunction.subscribe((emitted) => {
        if (emitted[0] == "btn") {
            this.ngOnInit();
        }
      });

of course you can avoid using the key, val way if you have only this button to check, but using this way you can subscribe to multiple buttons toggles or other variables.

  • Related