嘿,我是angularjs Im的新手,我在angularjs中使用controlleras样式,因为代码是可表示的并且是网络。我的问题是在 Controller 中调用子功能我的代码如下

 //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的实例,否则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>

10-07 16:31