简体   繁体   中英

angularjs how to pass parameters to named function from controller

Inside the controller I am trying to breakup my code into named functions for readability. However, in the parameterized named functions the scope and the injected dependency are all null. How do access these inside the named functions. Thanks for you help.

 ( function() { 'use strict'; var moduleName = 'ufsrAppModule'; var controllerName = 'ufsrController'; var dependencyInjection = ['api', 'appHost', 'userAccount', 'userProfileFactory', 'fsrFactory', 'userFsrFactory', internalFunc]; angular.module(moduleName) .controller(controllerName, dependencyInjection); function internalFunc(api, appHost, userAccount, userProfileFactory, fsrFactory, userFsrFactory) { var vm = this; //controller AS in ng-controller, do not use $scope init(api, appHost, userAccount, userProfileFactory, fsrFactory, userFsrFactory, vm); } function init(api, appHost, userAccount, userProfileFactory, fsrFactory, userFsrFactory, vm) { vm.facilityChanged = facilityChanged; ... ... function facilityChanged(vm, fsrFactory) { /*update UI then retrieve services*/ vm.postStatus = undefined; vm.services = undefined; vm.roles = undefined; vm.services = fsrFactory.service().query({ /*parameters*/ FacilityID: vm.facility }) .$promise.then( function(data) { vm.services = data; }); } } })(); 

Strict DI can be done separately in this style

angular.module(moduleName)
      .controller(controllerName, controllerFunction);

controllerFunction.$inject = ['$scope', '$http'];

function controllerFunction($scope, $http) {
  ...
}

This style is also recommended by John Papa's Angular style guide .

The facilityChanged is not working because its parameters are overwriting those that are passed into init

It can be fixed by changing

function facilityChanged(vm, fsrFactory) {

to

function facilityChanged() {

Edit: Attached jsbin

I strongly recommend putting the init function inside your controller function to save the parameter passing, just like the activate function in John Papa's guide.

Refined jsbin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM