在ControllerAs AngularJS中调用子函数

时间:2016-04-13 03:32:43

标签: angularjs angularjs-scope angularjs-controlleras

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

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

但警告并没有提前做好许多事情:(

2 个答案:

答案 0 :(得分:0)

您需要实例化helpM类:

替换:

vm.nineOne = helpM.SaveM

要:

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

答案 1 :(得分:0)

您必须制作helpM的实例,否则this将为undefined

&#13;
&#13;
(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);

})();
&#13;
<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>
&#13;
&#13;
&#13;