这个监听器最能说明问题:http://plnkr.co/edit/y3uacaQSc1MbrWKfb0At?p=preview

但是这是代码:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = testFactory.testFunction;

});

app.service('testFactory',function(){

  this.testFunction = function(){
    alert(test_var);
  };

})


并在html中:

<body ng-controller="MainCtrl">
    <p ng-click="testFunction()">Hello {{name}}!</p>

  </body>


现在,如您在plunkr中所看到的,test_var是未定义的,这是有道理的,因为未定义...所以我想从控制器传递它,但是如果我做类似的事情
$scope.testFunction = testFactory.testFunction(test_var);,则由于括号的原因,testFunction与警报一起执行。但是我只想传递test_var,而不执行函数。我怎样才能通过?

最佳答案

将调用包装在函数中,以便仅在testFactory.testFunction(test_var)为...时调用对$scope.testFunction()的调用。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = function() {
    testFactory.testFunction(test_var);
  };
});

app.service('testFactory',function(){

  this.testFunction = function(test_var){
    alert(test_var);
  };

})

09-11 18:26
查看更多