This plunker shows it best: http://plnkr.co/edit/y3uacaQSc1MbrWKfb0At?p=preview
but here is the code:
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);
};
})
and in the html:
<body ng-controller="MainCtrl">
<p ng-click="testFunction()">Hello {{name}}!</p>
</body>
right now, as you can see in the plunkr, test_var is undefined this makes sense because its not defined... So I want to pass it from the controller, but if I do something like $scope.testFunction = testFactory.testFunction(test_var);
, then the testFunction executes along with the alert because of the parentheses. But I just want to pass test_var, not execute the function. How can I pass it in?
Wrap the call in a function so that the call to testFactory.testFunction(test_var)
is only invoked when $scope.testFunction()
is...
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);
};
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.