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

时间:2014-09-27 11:11:05

标签: javascript angularjs url routes

我有一个像/products/:product_id

这样的网址

在此控制器中,我检查产品ID是否存在,然后,如果不存在,我想加载一个控制器,它将显示一些文本,如“找不到产品”。

我正在寻找一些功能:

$location.path('/product_not_found');

但不更改栏中的网址

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

angularjs可以向HTML标记添加属性。如果找到产品,如果没有,则我更喜欢使用ng-show属性。例如:

使用ng-show,您不会影响该网址,因为内容已经加载。

<强> 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();
    }]);
})();