代码之家  ›  专栏  ›  技术社区  ›  Jerry

如何定义角度方法

  •  0
  • Jerry  · 技术社区  · 8 年前

    我经常听取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()

    请帮忙!

    2 回复  |  直到 8 年前
        1
  •  0
  •   Bharat    8 年前

    如果希望将Logout函数公开给DOM(通过Angular),则需要将其放在$scope上。没有其他选项可以使用角度指令调用它(ng单击)。

    否则,如果希望在应用程序/控制器实例化之前调用它,请使用本机javascript的onclick()事件。

    警告:如果使用onclick,则无法设置$scope变量。

        2
  •  0
  •   Jerry    8 年前

    所以,多亏了巴拉特,我让它工作起来了!

    这就是解决方案:

        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调用包装在一个函数中,但问题已经得到了回答。

    我不能投你的赞成票,巴拉特,因为我还没有问足够的问题,但非常感谢!