2016-08-12 88 views
1

我有一個應用程序與2模塊1控制器(現在)和一個服務。角度1.5控制器在不同的.js文件

香港專業教育學院試圖把模塊和配置在這樣的文件:user.js

(function() { 
    'use strict'; 

    var app = angular.module('Users', ['ngRoute']); 

    app.config(['$routeProvider', '$locationProvider', config]); 
    app.controller('usersController', [usersController, UsersService]); 
    app.service('UsersService', ['$http', UsersService]); 

    function config($routeProvider, $locationProvider) { 
     $routeProvider 
      .when('/users', { 
      templateUrl: 'users/views/users-list.html', 
      controller: usersController 
      }) 
      .otherwise({redirectTo: '/'}); 
    } 


})(); 

然後控制器就像這樣:userController.js

(function() { 
    'use strict'; 

    var app = angular.module('Users'); 
    app.controller('usersController', usersController); 

    /* @ngInject */ 
    function usersController(UsersService) { 

     /*jshint validthis: true */ 
     var vm = this; 

     vm.names = [ 
      'Welder', 
      'Jéssica' 
     ]; 

     vm.findList = UsersService.findList() 
      .then(function(data) { 
       console.dir(data.data[0]); 
       vm.users = data.data; 
       console.log('vm: ', vm.users[0].name); 
      }); 
    } 
})(); 

,最後我的服務:usersService

(function() { 
    'use strict'; 

    var app = angular.module('Users'); 
    app.controller('usersService', usersService); 

    function UsersService($http) { 
     var BASE_URL = 'http://localhost:3000/api/users'; 

     this.create = create; 
     this.findList = findList; 
     this.find = find; 
     this.edit = edit; 
     this.remove = remove; 

     function create(user) { 
      var request = { 
       url: BASE_URL, 
       method: 'POST', 
       data: user 
      }; 
     return $http(request); 
     } 

     function findList() { 
      var request = { 
       url: BASE_URL, 
       method: 'GET' 
      }; 
      return $http(request); 
     } 

     function find(id) { 
      var request = { 
       url: BASE_URL + id, 
       method: 'GET', 
      }; 
      return $http(request); 
     } 

     function edit(user,id) { 
      var request = { 
       url: BASE_URL + id, 
       method: 'PUT', 
       data: user 
      }; 
      return $http(request); 
     } 

     function remove(id){ 
      var request = { 
       url: BASE_URL + id, 
       method: 'DELETE' 
      }; 
      return $http(request); 
     } 
    } 

})(); 

有人可以解釋爲什麼它neve r是否定義了分離的控制器或服務,即使我在我的index.html中同時聲明瞭這兩個控制器或服務?

回答

2

您的控制器和服務聲明與函數名稱不匹配(javascript區分大小寫),將服務聲明爲控制器並且缺少依賴項。

app.controller('usersService', usersService); 
    ^      ^
function UsersService($http) { 
     ^

應該是:

app.controller('usersController', ['usersService', usersController]); 

/* @ngInject */ 
function usersController(UsersService) { 

app.service('usersService', ['$http', UsersService]); 

function UsersService($http) { 

另外,不聲明控制器和users.js

服務