【问题标题】:AngularJS Data Binding controllersAngularJS 数据绑定控制器
【发布时间】:2018-09-29 06:08:53
【问题描述】:

我正在开发一个带有 Angular js 的 Spring Boot 应用程序并且遇到了困难。 我已经完成了入门应用程序的骨架,但是我在控制器 js 文件中遇到了问题。运行 spring boot 应用程序时出现白色空白屏幕。我在哪里出错了,还有一种更清洁或更有效的控制器编码方式吗?我将如何像我一直在做的那样添加不同的控制器?

    angular.module('myApp', ['ngRoute']).controller('shipwreckListController', function($scope, $state, popupService, $window, Shipwreck) {
    $scope.shipwrecks = Shipwreck.query(); // Fetch all shipwrecks, - issues a GET to api/vi/shipwrecks
    $scope.deleteShipwreck = function(shipwreck) {
        if(popupService.showPopup('Really delete this?')){
            shipwreck.$delete(function(){
                $scope.shipwrecks = Shipwreck.query();
                $state.go('shipwrecks');
            });
        }
    };
}).controller('shipwreckViewController', function($scope, $stateParams, Shipwreck){
    $scope.shipwreck = Shipwreck.get({id: $stateParams.id}); // get a single shipwreck. Issue a GET to /api/v1/shipwrecks/:id
}).controller('shipwreckCreateController', function($scope, $state, $stateParams, Shipwreck){
    $scope.shipwreck = new Shipwreck(); // create new shipwreck instance, properties will be set via ng-model on UI
    $scope.addShipwreck = function() {
        $scope.shipwreck.$save(function() {
            $state.go('shipwrecks'); // on success go back to the list
        });
    };
}).controller('shipwreckEditController', function($scope, $state, $stateParams, Shipwreck){
    $scope.updateShipwreck = function() {
        $scope.shipwreck.$update(function(){
            $state.go('shipwrecks');
        });
    };
    $scope.loadShipwreck = function() {
    $scope.shipwreck = Shipwreck.get({id: $stateParams.id})};

    $scope.loadShipwreck();

});

【问题讨论】:

  • 在你处理路由的地方添加 HTML 代码和 js 代码。

标签: angularjs spring-mvc spring-boot model-view-controller


【解决方案1】:

我之前没有使用过 Spring Boot,所以我不确定它为什么不能正确加载。 Shipwreck 和 popupService 的引用是否以某种方式通过 Spring Boot 注入?如果没有,您需要在模块声明中引用定义它们的模块。

关于您的第二个问题,设计一个“更清洁”和更“高效”的代码库需要您将“事物”拆分为它们自己的文件。基本上每个“事物”有 1 个文件。在这种情况下,每个控制器 1 个文件,模块声明 1 个文件。

模块本身是这样定义的:

angular.module('myApp', ['ngRoute', 'other dependency', 'another', 'etc']);

您可以使用以下语法将控制器(和其他东西)添加到您已经在另一个文件中定义的模块:

angular.module('myApp').controller(...);

然后您应该有一个捆绑过程,将模块中的所有相关文件组合到一个文件中。通常,这也会“缩小”您的 js 文件,这需要进一步调整您的代码以确保其“缩小安全”。 Angular 的依赖注入格式默认是不安全的。这是一个“缩小安全”控制器的示例:

angular
 .module('myApp')
 .controller('controllerName', ['$scope', '$state', 'etc', function($scope, $state, etc){
      //note that the index order of $scope
      //and other dependencies is important 1 matches 1, 2 matches 2, etc.
  }]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多