AngularJS变量未解析/显示

AngularJS variables not resolving/displaying

本文关键字:显示 变量 AngularJS      更新时间:2023-09-26

以下是相关的HTML:

<!DOCTYPE html>
<html ng-app="wpApp">
<body>
<div ng-controller="controllerMain as main">
    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav navbar-left">
            <li><a href="#">Link 1</a></li>
            <li><a href="#two">Link 2</a></li>
            <li><a href="#three">Link 3</a></li>
        </ul>
    </div>
    <!-- Start of View State -->
    <div class="page-content" style="padding-left:10px; padding-right:10px">
        <div ng-view></div>
    </div>
    <!-- End of View State -->
    <div class="footer">
        <div class="banner">
            {{main.message}}    
        </div>
    </div>
</div>
</body>
</html>

这是相关的Javascript

wpApp = angular.module("wpApp", ["ngRoute", "ngAnimate", "ui.bootstrap", "angularFileUpload"]);
wpApp.config(function($routeProvider) {
  return $routeProvider.when("/", {
    templateUrl: "one.html",
    controller: "controllerOne"
  }).when("/two", {
    templateUrl: "two.html",
    controller: "controllerTwo"
  }).when("/three", {
    templateUrl: "three.html",
    controller: "controllerThree"
  });
});
wpApp.controller("controllerMain", function() {
  this.ready = 'true';
  this.message = "This is the Main Controller";
  });
});

现在,一切都按照上面的方式设置好了(其他页面和所有页面都有一些额外的控制器(,controllerMain的消息会在HTML中的指定位置正确显示:"This is the Main Controller"。

现在,我需要在controllerMain中进行$http调用,所以我将其更改为:

wpApp.controller("controllerMain", function($http) {
  this.ready = 'true';
  this.message = "This is the Main Controller";
  return $http.get("config.json").success(function(data) {
    console.log("Here");
  });
});

当这种情况发生时,我可以在日志中看到"Here",但在应该显示"{{main.message}}"的地方没有显示任何内容。经过一点调试,我了解到,基本上,如果进行$httpGET调用,则不会显示任何内容。如果我取消呼叫,则会显示消息。

这里有什么问题?这与程序的配置方式有关吗?我是不是不了解控制器的工作方式?

请尝试删除您不需要从控制器返回任何东西的返回

wpApp.controller("controllerMain", function($scope, $http) {
  $scope.ready = 'true';
  $scope.message = "This is the Main Controller";
  $http.get("config.json").success(function(data) {
    console.log("Here");
  });
});

我还建议使用$scope.message = "This is the Main Controller";和在html {{message}}