【问题标题】:Why can't I use AngularJS to load a JSON file and angular route in the same page?为什么我不能使用 AngularJS 在同一页面中加载 JSON 文件和角度路由?
【发布时间】:2017-11-16 10:45:00
【问题描述】:

我不是母语人士,抱歉我的问题不清楚。 我正在尝试使用 AngularJS 来读取 JSON 文件。我做到了,但是当我在同一页面中使用角度路线时,角度路线没有运行。然后我发现我只能在一页中使用一个功能。为了更清楚,这是我的代码:

在 home.html 中:

<!DOCTYPE html>
<html ng-app="UpStore">
<head>


 </head>
 <body ng-controller="ProductController">

 <div ng-view> </div>

 <!--Javascript-->

 <script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-
route.js"></script>

<script src="js/app.js"></script>
<script>

    var app = angular.module("UpStore", [])
    app.controller("ProductController", function ($scope, $http) {
        $http({
            method: "GET",
            url: "productdata.json"
        }).then(function mySucces(respone) {
            $scope.products = respone.data
        }, function myError(respone) {
            $scope.dataError = respone.statusText
        }
            )
    })

 </script>

</body>
</html>

app.js:

var App = angular.module('UpStore', []);

App.controller('ProductController', function ($scope) {


});

var App = angular.module('UpStore', ['ngRoute']);


App.config(function ($routeProvider) {
$routeProvider



    .when('/men', {
        templateUrl: 'men.html',


    })


    .when('/product', {
        templateUrl: 'product.html',




    }).
    otherwise({
        redirectTo: 'men'
    });
});

App.controller('ProductController', function ($scope) {


});

在men.html中:

 <div ng-repeat="pd in products">
    <p>{{pd.ID}}</p>
    <p><a href="#product"><img src="image/{{pd.Image}}" /></a></p>
 </div>

我还有一个问题。在页面 men.html 中,我有几个产品,每个产品都有一个 ID。我有一个页面 product.html 来显示产品详细信息。我想要做的是当我单击页面men.html 中的产品图像时。 product.html 的 URL 类似于 product.html/productid。我知道$routeParams可以解决我的问题,但是我不知道怎么写代码。

我真的需要一些帮助,因为我已经为这两个问题苦苦挣扎了好几个小时。提前致谢。

【问题讨论】:

    标签: javascript html angularjs json


    【解决方案1】:

    您不断地覆盖先前定义的模块。

    因为您已经在 app.js

    中定义了模块 UpStore
    //Define it only once
    var App = angular.module('UpStore', ['ngRoute']);
    

    你需要在脚本块中获取它的引用并使用。

    //Get the reference to existing module
    var app = angular.module("UpStore"); 
    
    //Use it
    app.controller(.......)
    

    另外:注意始终使用相同版本的 angular.jsangular-route.js

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      相关资源
      最近更新 更多