3

Hey I am new to angularjs Im using controlleras style in angularjs as the code is presentable and net. My problem is calling subfunction in controller my code as follow

 //AngularJS CODE
      (function(){
         'use strict';

         angular.module('mAPP', ['ngMaterial']);

         function helpM(){
            var vm = this; 
            vm.SaveM = function(){
                alert('Save Me Now');
            }
         }

        function SaveCTRL(){
          var vm = this; 

          vm.nineOne = helpM.SaveM;
        }

        angular.module('mAPP')
                .controller('SaveCTRL', [SaveCTRL]); 

      })(); 

//HTML CODE

     <div ng-controller="SaveCTRL as main" layout="column" ng-cloak="" class="md-inline-form" ng-app="mAPP">


     <md-button class="md-raised md-primary" ng-click="main.nineOne()">Submit</md-button>

     </div>

But the alert doesnt execute thanks a lot in advance :(

jake talledo
  • 610
  • 11
  • 24

2 Answers2

0

You need to instantiate the helpM Class:

Replace:

vm.nineOne = helpM.SaveM

To:

var helpObj = new helpM();
vm.nineOne = helpObj.SaveM.bind(helpObj);
scyrizales
  • 134
  • 6
0

you have to make an instance of helpM otherwise this will be undefined

(function() {
  'use strict';

  angular.module('myApp', []);

  function helpM() {
    var vm = this;
    vm.SaveM = function() {
      alert('Save Me Now');
    }
    return vm;
  }


  function SaveCTRL() {
    var vm = this;

    vm.nineOne = new helpM().SaveM;

    return vm;
  }

  angular.module('myApp')
    .controller('SaveCTRL', SaveCTRL);

})();
<body ng-app="myApp">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <div ng-controller="SaveCTRL as main" layout="column" ng-cloak="" class="md-inline-form">


    <md-button class="md-raised md-primary" ng-click="main.nineOne()">Submit</md-button>

  </div>
</body>
Zhiliang Xing
  • 1,057
  • 1
  • 8
  • 19