角度工厂功能只执行一次

时间:2017-04-03 10:38:13

标签: javascript angularjs

我的角应用程序中有两个模块 module-1 module-2

module-1 中,我创建了一个工厂

angular.module('ui.campaign.manager').factory('validate',['the',function(the) {
return {
    validateOwner: function(scope) {
        console.log(scope.campaign);
        if(!scope.campaign.owner) {
          scope.view = true;
          scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
          return false;
        }
        return true;
    }
};

}]);

在模块2中,有一个控制器,我在ng-click

上调用此功能
var campaignApp = angular.module('module-2',[ 'module-1']);

campaignApp.controller('campaignDetailController', function($scope,    validate) {

    scope.submitCampaignPage = function(){
        validate.validateOwner($scope);
    }
});
<input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

现在,问题是我第一次单击“下一步”按钮 validateOwner 函数正在被调用,而后续点击后调用了submitCampaignPage函数,但是根本没有调用validateOwner函数

角度缓存结果是什么?

2 个答案:

答案 0 :(得分:0)

您需要将函数参数作为$scope而不是scope传递。

此外,请确保将scope.campaign声明为控制器或工厂中的对象,否则会引发异常,尝试访问未定义的属性

演示

&#13;
&#13;
angular.module("app",[])
.controller("ctrl",function($scope,validate){
$scope.campaign = {}
  $scope.submitCampaignPage = function(){
    console.log(validate.validateOwner($scope))
 }

}).factory('validate',function() {
  return {
      validateOwner: function(scope) { 
          if(!scope.campaign.owner) {
            scope.view = true;
            scope.errormsg = "Error : Campaign owner is a mandatory field. Please select one from the dropdown menu.";
            return false;
          }
          return true;
      }
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input class="btn btn-primary" type="submit" value="Next" name="campdetailsnext" ng-click="submitCampaignPage()">

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您是否尝试将控制器和工厂放在同一模块上进行测试?因为我只是尝试在同一个模块上使用控制器和工厂,它工作得很好。