【问题标题】:Unable to get controller loaded into my angularjs module无法将控制器加载到我的 angularjs 模块中
【发布时间】:2016-10-04 14:54:13
【问题描述】:

我正在尝试将我的 angularjs 控制器拆分为文件,但每次都失败。

目录结构:

--public--
        --js/controller/resturant.js
        --js/master.js
        --index.php

master.js 的代码

angular.module("rsw",['rsw.controller']);

resturant.js 的代码

    angular.module('rsw.controller').controller('resturant', ['$scope', '$http', function($scope, $http){
    $scope.data="Test"
}]);

index.php 的代码

--
<div ng-app="rsw">
  <span ng-controller="resturant">
    {{ data }}
  </span>
</div>
--

编辑: 我的 index.php 中只包含了“master.js”,我还需要导入“resturant.js”吗?

【问题讨论】:

  • 您已经创建了一个模块“rsw”并在另一个模块“rsw.controller”模块中创建了您的控制器。您是否在 'rsw' 模块中添加了 'rsw.controller' 模块作为依赖项?
  • 是的,还是不行

标签: javascript angularjs model-view-controller angularjs-controller


【解决方案1】:

您需要使用正确的module definition 调用。也就是说,angular.module(name)检索一个模块,angular.module(name, [requires])创建一个。

angular.module('rsw.controller', [])
.controller('resturant', ['$scope', '$http', function($scope, $http){
    $scope.data="Test"
}]);

创建模块后,您需要使其成为您应用的依赖项:

angular.module("rsw",['rsw.controller']);

固定代码:

angular.module("rsw", ['rsw.controller']);
angular.module('rsw.controller', [])
  .controller('resturant', ['$scope', '$http',
    function($scope, $http) {
      $scope.data = "Test"
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="rsw">
  <span ng-controller="resturant">
    {{ data }}
  </span>
</div>

【讨论】:

  • 我现在收到此错误:Uncaught Error: [$injector:modulerr]
  • @JaskaranSinghPuri 在我的回答中有一个小错字,忘记了'rsw.controller', [] 中的,。可能是这个原因吗?
  • @JaskaranSinghPuri 我添加了一个包含您的代码的sn-p,上面只发布了我的更改,它可以工作。如果您有错误,请分享完整的错误 + 堆栈。
  • 这是一个单文件代码,我想把我的控制器拆分成不同的文件!
  • @JaskaranSinghPuri 它将以完全相同的方式处理多个文件。如果您一个接一个地有 2 个
【解决方案2】:

我认为您的控制器设置错误。 请尝试输入以下内容:

angular.module('rsw').controller('resturant', ['$scope', '$http', function($scope, $http){
    $scope.data="Test"
 }]);

【讨论】:

  • 哦,是的,另一个错误输入问题,试试这样:angular.module('rsw').controller('resturant', function ($scope, $http){ $scope.data="Test" });
【解决方案3】:

这样的东西应该可以工作......

文件结构:

--public
  --js
    --controllers
      --resturant.js
    --app.js
    --appRoutes.js
--views
  --index.php

// resturant.js
    angular.module('rswCtrl', []).controller('RswController', [$scope, function($scope) {

}]);

 // appRoutes.js

   angular.module('appRoutes', []).config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/index.php',
      controller: 'RswController' 
    });
  }]);

// app.js
angular.module('myApp', ['appRoutes', 'rswCtrl']);

然后不要忘记在 index.php 文件中包含所有这些文件的路径。希望我没有遗漏什么..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2015-02-09
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2014-09-16
    相关资源
    最近更新 更多