0

我正在尝试在运行时在 dom 对象上设置控制器:

此处的示例代码:http: //jsfiddle.net/2FL3z/3/

<div id="ctrl1">
    <p>{{message}}</p>
    <a href="#/view1" class="btn">{{btn1}}</a>
    <a href="#/view2" class="btn">{{btn2}}</a>
</div>

<div id="ctrl2">
    <p>{{message}}</p>
    <a href="#/view1" class="btn">{{btn1}}</a>
    <a href="#/view2" class="btn">{{btn2}}</a>
</div>
/* CONTROLLER 1 (first.js) */
define([], function () {

    function FirstController($scope) {
        $scope.message = "I'm the 1st controller!";
        $scope.btn1 = "Ctrl1 Btn 1";
        $scope.btn2 = "Ctrl1 Btn 2";
    }

    // Get a reference to div#ctrl1 and apply this controller to it.
    return FirstController;
});


/* CONTROLLER 2 (second.js) */
define([], function () {

    function SecondController($scope) {
        $scope.message = "I'm the 2nd controller!";
        $scope.btn1 = "Ctrl2 Btn 1";
        $scope.btn2 = "Ctrl2 Btn 2";
    }

     // Get a reference to div#ctrl2 and apply this controller to it.
    return SecondController;
});
<!-- Expected Output -->
<div id="ctrl1" ng-controller='FirstController'>
    <p>I'm the 1st controller!</p>
    <a href="#/view1" class="btn">Ctrl1 Btn 1</a>
    <a href="#/view2" class="btn">Ctrl1 Btn 2</a>
</div>

<!-- References $scope of ctrl2 -->
<div id="ctrl2" ng-controller='FirstController'>
    <p>I'm the 2nd controller!</p>
    <a href="#/view1" class="btn">Ctrl2 Btn 1</a>
    <a href="#/view2" class="btn">Ctrl2 Btn 2</a>
</div>

关于如何让它发挥作用的任何建议。我正在使用https://github.com/matys84pl/angularjs-requirejs-lazy-controllers但看起来整个应用程序都根据路由路径获取控制器。我需要将应用程序分成由不同控制器控制的部分。

我读过它不赞成在控制器中修改 dom,所以我正在寻找最佳实践——也许在 routes.js 中指定 dom 元素:

routeConfig.config('../partials/view1.html', 'controllers/first', '#someDomElementID')

我不认为 angularjs-requirejs-lazy-controllers 是这样设置的。

谢谢!

4

0 回答 0