2016-09-05 32 views
0

我是來自Stackoverflow的常規消費者建議。這是一個非常寶貴的工具 - 感謝所有的幫助!如何定義角度方法

但是這是我的第一個問題:我對Angular很陌生,但我一直在爲驢子做服務器端的東西。

我有一個控制器上的方法,它調用服務器REST服務。我的問題是,只要控制器被實例化,就會調用該方法。我知道必須有另一種聲明函數的方式,但我不知道要搜索什麼。

這裏是我的html:

<html lang="en" data-ng-app="mLS" ng-controller="mLSController"> 
<head>....</head> 
... 
<li><a ng-if="userName" ng-click="Logout()">logout</a></li> 

和我的模塊(模塊DEF是其他地方,但它似乎確定)

var app = angular.module('mLS'); 
app.controller('mLSController', function ($scope, $http, $window, $location) { 
    $http({ 
     url: '/api/UI/GetUsername', 
     method: 'GET' 
    }).success(function (data, status, headers, config) { 
     $scope.userName = data; 
     $scope.desiredPath = $location.path(); 

     if (!$scope.userName && $scope.desiredPath != '/Account/Login') 
      $window.location.href = '/Account/Login'; 
    }); 
}); 

function Logout($http) { 
    $http({ url: '/api/UI/Logout', method: 'GET' }); 
} 
//app. 
// controller('mLSController', function ($scope, $http) { 
//  $scope.Logout = function() { 
//   $http({ url: 'api/UI/Logout', method: 'GET' }); 
//  }; 
// }); 

//app. 
// controller('mLSController', ['$scope', '$http', 'Logout', function ($scope, $http, Logout) { 
//  $scope.callLogout = function() { 
//   Logout(); 
//  }; 
// }]). 
// factory('Logout', ['$http', function (protocol) { 
//  protocol({ url: 'api/UI/Logout', method: 'GET' }).success(function() { 
//   $scope.Logout = true; }); 
// }]); 

所以我的問題是,當前的代碼:

function Logout($http) { 
     $http({ url: '/api/UI/Logout', method: 'GET' }); 
} 

只是根本不叫,如果我把它放在控制器上,Logout()被稱爲co時ntroller被實例化。哪個不理想。

請幫忙!

回答

0

如果你想讓Logout函數暴露給DOM(通過Angular),你需要把它放在$ scope上。沒有其他選擇使用角度指令來調用它(ng-click)。除此之外,如果您希望在實例化應用程序/控制器之前調用它,請使用原生javascript的onclick()事件。

警告:如果您使用onclick,則無法設置$ scope變量。

0

所以,感謝Bharat,我已經得到了它的工作!

這是解決方案:

var app = angular.module('mLS'); 
    app.controller('mLSController', 


     // function added to the controller 
     function ($scope, $http, $window, $location) { 
      $scope.Logout = function() { 
       $http({ url: 'api/UI/Logout', method: 'GET' }); 
      return ; 
     }; 


    $http({ url: '/api/UI/GetUsername', method: 'GET' }).success(function (data, status, headers, config) { 
     $scope.userName = data; 
     $scope.desiredPath = $location.path(); 

     if (!$scope.userName && $scope.desiredPath != '/Account/Login') 
      $window.location.href = '/Account/Login'; 
    }); 
}); 

爲了完整起見,我可以換一個函數的調用GetUsername,但問題是回答。

因爲我還沒有提出足夠的問題,所以我不能滿足您的答案,Bharat,但非常感謝!

+0

沒問題隊友:) – Bharat