2016-02-01 3 views
-1

Этот вопрос кажется очень распространенным. Но я долгое время не мог найти проблему. Я распространил приложение, контроллер, модули обслуживания в отдельные файлы js, как показано ниже.

app.js

/** Main AngularJS Web Application */ 
var app = angular.module('ngdemo', [ 'ngdemo.controllers', 'ngdemo.services' ]); 

app 
     .config([ 
       '$routeProvider', 
       '$httpProvider', 
       function($routeProvider, $httpProvider) { 

        $routeProvider.when('/documents', { 
         templateUrl : 'documents.html', 
         controller : 'documentListCtrl' 
        }).when('/documents/:id', { 
         templateUrl : 'edit_document.html', 
         controller : 'documentDetailCtrl' 
        }).when('/document', { 
         templateUrl : 'create_document.html', 
         controller : 'documentCreationCtrl' 
        }).otherwise({ 
         redirectTo : '/home' 
        }); 

        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; 
       } ]); 

и document_controllers.js

var controllers = angular.module('ngdemo.controllers', []); 

/* ... */ 
controllers.controller('navigation', ['$rootScope', '$scope', '$http', '$location', '$route', function($rootScope, $scope, $http, $location, $route) { 

    $scope.tab = function(route) { 
     return $route.current && route === $route.current.controller; 
    }; 

    var authenticate = function(credentials, callback) { 

     var headers = credentials ? { 
      authorization : "Basic " 
        + btoa(credentials.username + ":" 
          + credentials.password) 
     } : {}; 

     $http.get('user', { 
      headers : headers 
     }).success(function(data) { 
      if (data.name) { 
       $rootScope.authenticated = true; 
      } else { 
       $rootScope.authenticated = false; 
      } 
      callback && callback($rootScope.authenticated); 
     }).error(function() { 
      $rootScope.authenticated = false; 
      callback && callback(false); 
     }); 

    } 

    authenticate(); 

    $scope.credentials = {}; 
    $scope.login = function() { 
     authenticate($scope.credentials, function(authenticated) { 
      if (authenticated) { 
       console.log("Login succeeded") 
       $location.path("/documents"); 
       $scope.error = false; 
       $rootScope.authenticated = true; 
      } else { 
       console.log("Login failed") 
       $location.path("/home"); 
       $scope.error = true; 
       $rootScope.authenticated = false; 
      } 
     }) 
    }; 

    $scope.logout = function() { 
     $http.post('logout', {}).success(function() { 
      $rootScope.authenticated = false; 
      $location.path("/"); 
     }).error(function(data) { 
      console.log("Logout failed") 
      $rootScope.authenticated = false; 
     }); 
    } 

}]); 

/* ... */ 
controllers.controller('documentListCtrl', ['$scope', 'DocumentsFactory', 'DocumentFactory', '$location', 
    function ($scope, DocumentsFactory, DocumentFactory, $location) { 

     // callback for ng-click 'editDocument': 
     $scope.editDocument = function (documentId) { 
      $location.path('/documents/' + documentId); 
     }; 

     // callback for ng-click 'deleteDocument': 
     $scope.deleteDocument = function (userId) { 
      DocumentFactory.delete({ id: userId }); 
      $scope.documents = DocumentsFactory.query(); 
     }; 

     // callback for ng-click 'createDocument': 
     $scope.createNewDocument = function() { 
      $location.path('/document'); 
     }; 

     $scope.documents = DocumentsFactory.query(); 
    }]); 


/* ... */ 
controllers.controller('documentDetailCtrl', ['$scope', '$routeParams', 'DocumentFactory', '$location', 
    function ($scope, $routeParams, DocumentFactory, $location) { 

     // callback for ng-click 'updateDocument': 
     $scope.updateDocument = function() { 
      DocumentFactory.update($scope.document); 
      $location.path('/documents'); 
     }; 

     // callback for ng-click 'cancel': 
     $scope.cancel = function() { 
      $location.path('/documents'); 
     }; 

     $scope.document = DocumentFactory.show({id: $routeParams.id}); 
    }]); 

/* ... */ 
controllers.controller('documentCreationCtrl', ['$scope', 'DocumentsFactory', '$location', 
    function ($scope, DocumentsFactory, $location) { 

     // callback for ng-click 'createNewUser': 
     $scope.createNewDocument = function() { 
      DocumentsFactory.create($scope.document); 
      $location.path('/documents'); 
     } 
    }]); 

и, наконец, document_services.js

var services = angular.module('ngdemo.services', ['ngResource']); 

services.factory('DocumentsFactory', function ($resource) { 
    return $resource('/rest/documents', {}, { 
     query: { method: 'GET', isArray: true }, 
     create: { method: 'POST' } 
    }) 
}); 

services.factory('DocumentFactory', function ($resource) { 
    return $resource('/rest/documents/:id', {}, { 
     show: { method: 'GET' }, 
     update: { method: 'PUT', params: {id: '@id'} }, 
     delete: { method: 'DELETE', params: {id: '@id'} } 
    }) 
}); 

В моем файле index.html,

<!doctype html> 
<html> 

<head> 
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> 
<meta name="description" content=""> 
<meta name="author" content=""> 
<link rel="icon" href="favicon.ico"> 

<title>Sample Project</title> 

<link href="css/bootstrap.min.css" rel="stylesheet"> 
<link href="css/jumbotron.css" rel="stylesheet"> 

</head> 



<body ng-app="ngdemo" class="ng-cloak"> 

    <nav class="navbar navbar-inverse navbar-fixed-top"> 

     <!-- ng-controller="navigation" --> 
     <div class="container"> 
      <div class="navbar-header"> 

       <a class="navbar-brand" href="#">Project name</a> 
      </div> 
      <div id="navbar" class="navbar-collapse collapse"> 

       <ul class="nav navbar-nav"> 

        <li ng-class="{active:tab('home')}"><a href="#/">Home</a></li> 
        <li ng-show="authenticated" ng-class="{active:tab('document')}"><a 
         href="#/documents">Document</a></li> 
       </ul> 

       <form ng-show="!authenticated" ng-submit="login()" 
        class="navbar-form navbar-right"> 
        <div class="form-group"> 
         <input type="text" class="form-control" id="username" 
          name="username" ng-model="credentials.username" /> 
        </div> 
        <div class="form-group"> 
         <input type="password" class="form-control" id="password" 
          name="password" ng-model="credentials.password" /> 
        </div> 
        <button type="submit" class="btn btn-success">Sign in</button> 
       </form> 

       <div ng-show="authenticated" ng-submit="login()" 
        class="navbar-form navbar-right"> 
        <button type="submit" class="btn btn-success" ng-click="logout()">Log 
         Out</button> 
       </div> 

      </div> 
     </div> 
    </nav> 

    <div ng-view class="container"></div> 

    <script src="js/angular-bootstrap.js" type="text/javascript"></script> 


    <script src="js/app.js"></script> 
    <script src="js/document_controllers.js"></script> 
    <script src="js/document_services.js"></script> 

</body> 
</html> 

В моем проекте я использую wro4j-maven-plugin для создания файлов JavaScript

<groups xmlns="http://www.isdc.ro/wro"> 
    <group name="angular-bootstrap"> 
    <css>webjar:bootstrap/3.2.0/less/bootstrap.less</css> 
    <css>file:${project.basedir}/src/main/wro/main.less</css> 
    <js>webjar:jquery/2.1.1/jquery.min.js</js> 
    <js>webjar:angularjs/1.3.8/angular.min.js</js> 
    <js>webjar:angularjs/1.3.8/angular-route.min.js</js> 
    <js>webjar:angularjs/1.3.8/angular-cookies.min.js</js> 
    </group> 
</groups> 

Таким образом, этот сгенерированный angular-bootstrap файл правильно ссылаться в HTML файл, но до сих пор загрузка модулей кажется, терпит неудачу. Любая помощь очень ценится.

Благодаря

+0

угловой ресурс включен в index.html? – Avinash

+0

@ Авинаш вы можете объяснить больше? – Jane

+0

Что-то вроде этого Avinash

ответ

0

Вы, вероятно, необходимо установить поставщика маршрута и включают ngRoute Зависимость от в ваших app.js.

Вот документация: $routeProvider

И об установке: ngRoute

Смежные вопросы