一个控制器可处理多页

时间:2018-07-03 22:49:55

标签: javascript angularjs

我用$ routeProvider制作了一个带有路由的网站,我为每个页面制作了控制器,它看起来像:

   myApp.config(function ($routeProvider) {
     $routeProvider
         
         .when('/category/Web development', {
            templateUrl: 'pages/web-dev.html',
            controller: 'catCtrl'
        })
         .when('/category/Game Programming', {
            templateUrl: 'pages/game-programming.html',
            controller: 'catCtrl2'
        })
     
     myApp.controller('catCtrl', function ($scope, $http) {
        $http.get("http://localhost/biblioteka/public/index/web-dev")
         .then(function (response) {
            $scope.books = response.data;
     });
 $http.get("http://localhost/biblioteka/public/category" )
     .then(function (response) {
         $scope.categories = response.data;
     });
     $scope.login = false;
     $scope.hideLogin = true;
     $scope.showLoginDiv = function() {
        $scope.login = $scope.login? false : true;
        $scope.hideLogin = $scope.hideLogin? false : true;
     };
     $scope.closeLoginDiv = function () {
        $scope.login  = false;
        $scope.hideLogin = true;
     };
     $scope.isPassword = function () {
         if ($scope.passwordValidation === "123456789") {
            $scope.login  = false;
            $scope.hideLogin = true;
            
         } else  {
            alert("Wrong password. Try again!");
         };
     };
   });
 myApp.controller('catCtrl2', function ($scope, $http) {
   $http.get("http://localhost/biblioteka/public/index/game-programming")
    .then(function (response) {
        $scope.books = response.data;
    });
 $http.get("http://localhost/biblioteka/public/category")
    .then(function (response) {
        $scope.categories = response.data;
    });
    $scope.login = false;
    $scope.hideLogin = true;
    $scope.showLoginDiv = function() {
       $scope.login = $scope.login? false : true;
       $scope.hideLogin = $scope.hideLogin? false : true;
    };
    $scope.closeLoginDiv = function () {
       $scope.login  = false;
       $scope.hideLogin = true;
    };
    $scope.isPassword = function () {
        if ($scope.passwordValidation === "123456789") {
           $scope.login  = false;
           $scope.hideLogin = true;
           
        } else  {
           alert("Wrong password. Try again!");
        };
    };
  });

如您所见,两个控制器具有相同的内容,但是我只想为不同的页面制作一个控制器,请问我该怎么做?我试图在$ routeProvider中设置相同的控制器,但是它不起作用:(

1 个答案:

答案 0 :(得分:0)

我认为您最好的方法是这样的:

#!