【问题标题】:HTML page doesn't see AngularJS moduleHTML 页面看不到 AngularJS 模块
【发布时间】:2015-08-13 07:10:03
【问题描述】:

我对 AngularJS 完全陌生。然而,任务很简单:从 url 解析 XML 文件并用它制作一个表格。

但不知何故,角度不加载。我搜索了类似的问题,但都没有奏效。我的 index.html:

 <!doctype html>
<html ng-app="myApp">
<head>
<title>jj</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular.intellisense.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/myscript.js"></script>

</head>
<body>
<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">Text.</p>

</div>
    <div ng-controller="AppController">


        <h3>for example 2+3= {{3+2}}</h3>

    </div>
 </div>
 </body>
 </html>

如果加载了 angular,我应该得到 5 而不是 2+3? myscript.js 目前看起来像:

  angular.module('myApp.service', []).
myApp.factory('DataSource', ['$http', function ($http) {
    return {
        get: function(file,callback,transform){
            $http.get(
                file,
                {transformResponse:transform}
            ).
            success(function(data, status) {
                console.log("Request succeeded");
                callback(data);

            }).
            error(function(data, status) {
                console.log("Request failed " + status);

            });

        }           
    }
}]);

angular.module('myApp', ['myApp.service']);
var AppController = function ($scope, DataSource) {

var SOURCE_FILE = "guitars.xml";

xmlTransform = function (data) {
    console.log("transform data");
    var x2js = new X2JS();
    var json = x2js.xml_str2json(data);
    return json.customers.customer;
};    
setData = function (data) {
    $scope.dataSet = data;
 };
  DataSource.get(SOURCE_FILE, setData, xmlTransform);
 };

你能给我一些建议吗?

【问题讨论】:

  • 您是否尝试将 ng-app="myApp" 移动到 标签而不是 ?

标签: javascript html angularjs xml-parsing


【解决方案1】:

这与您的语法有关。我相信你有2个错误。在您的 myscript.js 中,您声明了 2 个模块。在您的第一个模块中,您错误地声明了工厂。使用.factory 而不是myApp.factory

angular.module('myApp.service', [])
.factory('DataSource', ['$http', function ($http) {
  return {
    // do something
  }
}]);

在您的第二个模块中,您声明了一个名为 AppController 的函数,而不是调用 .controller 角度方法。改为这样做:

angular.module('myApp', ['myApp.service'])
.controller('AppController', ['$scope', 'DataSource', function ($scope, DataSource) {

  // controller code

}]);

【讨论】:

  • 谢谢!解决了。另一个问题:如果链接是 ....api/customers.xml,我的 var SOURCE_FILE = "/api/customers.xml" 是否正确,并且获取 xml 的方法是否相同?
【解决方案2】:

您可以使用类似于以下内容的结构在一个单独的模块中完成您的程序:

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

app.controller('AppController', function($scope, DataSource) {
  // code
});

app.factory('DataSource', ['$http', function($http) {
  // code
}]);

基本上,为您的应用模块创建一个变量,然后调用控制器和工厂,并将您的工厂传递给您的控制器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2020-03-18
    • 2016-11-05
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多