在 ControllerAs 中调用子函数 AngularJS

Calling sub function in ControllerAs AngularJS

嘿,我是 angularjs 的新手,我在 angularjs 中使用控制器样式,因为代码是可呈现的和网络的。我的问题是在控制器中调用子函数我的代码如下

 //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 代码

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

但是警报没有执行提前非常感谢:(

您需要实例化 helpM Class:

替换:

vm.nineOne = helpM.SaveM

收件人:

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

您必须创建 helpM 的实例,否则 this 将是 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>