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 :(

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

so treat a function like a class that needs to be instance to get the value of this ? thanks it works
0

You need to instantiate the helpM Class:

Replace:

vm.nineOne = helpM.SaveM

To:

var helpObj = new helpM();
vm.nineOne = helpObj.SaveM.bind(helpObj);

1 Comment

thanks but I encounter an error it says Cannot read property 'bind' of undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.