AngularJs在运行时在Dom上设置控制器

时间:2013-03-12 19:17:44

标签: angularjs lazy-loading

我正在尝试在运行时在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是这样设置的。

谢谢!

0 个答案:

没有答案