angularjs如何在不更改url的情况下加载另一个控制器

angularjs how to load another controller without change the url

本文关键字:情况下 加载 另一个 控制器 url angularjs      更新时间:2023-09-26

我有一个类似/products/:product_id 的URL

在这个控制器中,我检查产品id是否存在,然后,如果不存在,我想加载一个控制器,它会显示一些文本,比如"找不到产品"。

我正在寻找一些功能,比如:

$location.path('/product_not_found');

但不更改条中的URL

知道吗?

谢谢!

angularjs可以为HTML标记添加属性。在显示产品(如果找到)和消息(如果没有)的情况下,我更喜欢使用ng-show属性。例如:

使用ng-show不会影响URL,因为内容已经加载。

HTML:

<html ng-app="productDisplay">
<head>
    <title>Product info</title>
    <script src="js/angular.js"></script>
    <script src="js/app.js"></script>
</head>
<body>
    <div id="content" ng-controller="ProductController as productCtrl">
        <div ng-show="status === 'waiting'">
            <p>waiting for product to load..</p>
        </div>
        <div ng-show="status === 'found'">
            <!-- display product info here -->
            <p>Name: {{ product.name }}</p>
            <p>Price: {{ product.price }}</p>
        </div>
        <div ng-show="status === 'not-found'">
            <p style="color: red;">Not found such product</p>   
        </div>
    </div>
</body>
</html>

JS:

(function() {
    // can access varibal app only in this function scope
    var app = angular.module('productDisplay', []);
    app.controller('ProductController', ['$scope', function($scope) {
        $scope.product = {name: '', price: ''};
        $scope.status = 'waiting';
        this.getProduct = function() {
            found = false;
            /** some code checking if product found */
            if (!found) {
                $scope.status = 'not-found';
                return {};
            } else {
                $scope.status = 'found';
                return {name: 'BBB', price: '123$'};
            }
        };
        $scope.product = this.getProduct();
    }]);
})();