我有一个控制器可以正常切换隐藏并在此阶段显示div元素我正在尝试清理所以我开始使用服务。
内置切换方法的控制器代码段
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = function (){
$scope.myVar = !$scope.myVar
//once toggled i.e form taken away success or failure message displayed for x time
$scope.successOrFailureAlert = true;
$timeout(function () {$scope.successOrFailureAlert = false}, 2000)
}
})
服务
app.service('Service', function($timeout){
var user = ""
var location = ""
this.toggle = function(var1,var2){
console.log(var1)
console.log(var2)
var1 = !var1
var2 = true;
$timeout(function () {var2 = false}, 2000)
}
})
添加了服务的控制器
app.controller('addFormCtrl', function($scope, $http, $timeout, Service){
$scope.myVar = true
$scope.toggle = Service.toggle($scope.myVar, $scope.successOrFailureAlert)
//function (){
// $scope.myVar = !$scope.myVar
// once toggled i.e form taken away success or failure message displayed for x time
// $scope.successOrFailureAlert = true;
// $timeout(function () {$scope.successOrFailureAlert = false}, 2000)
//}
})
当我使用服务而不是在那里定义方法时。切换不会发生任何事情。我希望我有更多关于上下文信息的补充
HTML
<div ng-controller="addFormCtrl">
<span ng-show="successOrFailureAlert"> {{status}} </span>
<button ng-click="toggle()"> Add Employee </button>
<form ng-hide="myVar" ng-submit="submitAddEmployeeForm()">
<input type="text" ng-model="name">
<input type="text" ng-model="country">
<input type="submit" value="Submit" />
</form>
</div>
答案 0 :(得分:1)
在函数内部调用它,因为 ng-click
需要一个函数。
$scope.toggle = function(){
Service.toggle($scope.myVar, $scope.successOrFailureAlert);
}