如何动态更改控制器和模板?

时间:2013-11-24 08:11:09

标签: angularjs

我有一个如下页面,并且想要根据“cms-header”中动态点击的项目更改控制器和“cms-content”模板。

这样做有好办法吗?我不喜欢使用$ routeProvider。

<div id="cms-header"  ng-controller="CmsMenuCtrl">

</div>
<div id="cms-content">

</div>

2 个答案:

答案 0 :(得分:1)

我建议您为每个子模板使用ng-include和单独的控制器。

所以,它看起来像这样:

<div ng-controller="CmsMenuCtrl">
    <div id="cms-header">
        <button ng-click="select(0)">Product Details</button>
    </div>
    <div id="cms-content" ng-include="content"></div>
</div>

CmsMenuCtrl

myApp.controller('CmsMenuCtrl', function($scope) {

    $scope.content = null;

    $scope.pages = ['productDetails.html', 'categories.html', 'checkout.html'];

    $scope.select = function(idx) {

        $scope.content = $scope.pages[idx]; // obviously index isn't the best way :)
    }
});

然后在productDetails.html模板中输入以下内容:

<div ng-controller="productDetailsCtrl">

  <!-- All the information on the scope of productDetailsCtrl -->
</div>

答案 1 :(得分:1)

如果您有多个选择,那么您可以使用ng-switch来执行此操作。关于它的好处是你将在模板本身中拥有所有与模板相关的信息。

<强>模板

<div id="cms-header" ng-controller="CmsMenuCtrl">
    <nav>
        <button ng-click="selectItem('about')">About</button>
        <button ng-click="selectItem('home')">Home</button>
    </nav>
</div>

<div id="cms-content" ng-controller="CmsContentCtrl">

    <div ng-switch="selectedItem()">
        <div ng-switch-when="about">
            <div ng-include="'about.html'" 
                 ng-controller="CmsAboutCtrl">
            </div>
        </div>

        <div ng-switch-when="home">
            <div ng-include="'home.html'" 
                 ng-controller="CmsHomeCtrl">
            </div>
        </div>

        <!-- Other pages -->

    </div>
</div>

分享导航信息的服务

这是$routeParameters

的替代品
// navigationService to share information across controllers
myApp.service('navigationService', function () {
    var currentItem;

    this.selectItem(item) = function (item) {
        currentItem = item;
    };

    this.selectedItem() = function () {
        return item;
    };
});

<强>控制器

myApp.controller('CmsMenuCtrl', function ($scope, navigationService) {

    // ...

    $scope.selectItem = function (item) {
        navigationService.selectItem(item);
    };
});

myApp.controlelr('CmsContentCtrl', function ($scope, navigationService) {
    $scope.selectedItem = function () {
        return navigationService.selectedItem();
    }
});

请注意,如果您可以定义包含两个组件的控制器,然后避免服务。但是,使用naviagtionService将是首选方式。