在页面上多次使用同一个控制器的最佳做法是什么

时间:2015-11-06 04:47:09

标签: angularjs

当您使用$ codesign -f -s - SDL2 将控制器分配给DOM上的元素时,它只能在该元素内部工作。例如:

ng-controller

但是,如果将控制器分配给指令,则控制器可以在使用指令的页面上的任何位置工作。例如:

<section ng-controller="ExampleCtrl as example">
    <h1>Example Controller Works Here</h1>
    {{example.item}}
</section>

<section>
    <h1>But Not Here</h1>
    {{example.item}} <!-- Nothing -->
</section>

我想知道我是否在指令中使用控制器并且需要在页面的不同部分访问它是否可以依赖指令,或者最好再次声明它?

app.directive('exampleDirective', function(){
    return {
        ...
        controller: 'ExampleCtrl',
        controllerAs: 'example'
    };
});

<section>
    <div example-directive>
        <h1>Example Controller Works Here</h1>
        {{example.item}}
    </div>
</section>

<section>
     <h1>And Example Controller Works Here Too</h1>
     {{example.item}}
</section>

此外,如果我再次声明它会导致同一控制器的重叠功能出现任何问题吗?

我没有询问是什么让代码更清晰或更容易阅读。我理解如果我删除指令以及它如何远离Angular的medullar设计,那么页面上的其他元素的功能会有破坏的危险。从严格的功能角度来看,我想知道这两种方法都存在危险。

0 个答案:

没有答案