3

嘿,我是 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代码

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

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

4

2 回答 2

0

你必须做一个实例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>

于 2016-04-13T03:51:07.217 回答
0

您需要实例化 helpM 类:

代替:

vm.nineOne = helpM.SaveM

至:

var helpObj = new helpM();
vm.nineOne = helpObj.SaveM.bind(helpObj);
于 2016-04-13T03:36:43.140 回答