Angular ngController 与在指令中构建的控制器 [英] Angular ngController vs Controller constructed within Directive

查看:19
本文介绍了Angular ngController 与在指令中构建的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这两种创建控制器的方法的用例是什么:

I'm wondering what the use cases are for these two methods of creating a controller:

使用 ngController:

myApp.controller('myController', ['$scope', function ( $scope ) {

}]);

在具有控制器属性的指令中构造控制器:

myApp.directive ( 'myDirective', [ '$window', function( $window ) {
    return {
        restrict: 'A',
        controller: [ '$scope', function( $scope ) {

        }],
        link: function( scope, element, attrs ) {

        }
    };
}]);

如果它们都在同一个元素上被调用,那么您是否有理由不在指令中构造控制器?

Is there any reason you wouldn't construct the controller within a directive if they were both invoked on the same element?

这仅仅是控制器使用范围/复杂程度的问题吗?

Is it simply a question of how widely used / complex the controller is?

推荐答案

使用directive controller的理由,一句话浓缩:

The reason to use directive controller is condensed in one sentence:

创建可重用的组件

指令控制器应该包含可以重用的组件逻辑.将指令控制器与隔离作用域一起使用是创建可重用组件的方法.

Directive controller should contain logic of the component that could be reused. Using directive controller together with isolate scope is the way to create reusable components.

以分页器为例:分页器需要一些逻辑来通知其他组件(例如网格)当前选定的页面已更改,以便网格可以相应地更新.这些逻辑可以写在指令控制器中重用.与isolate scope一起使用时,此范围对应用程序控制器的范围并不严格,而且您可以轻松配置pageSize 绑定到应用程序控制器范围的任何属性.

Take a paginator as an example: a paginator needs some logic to notify other component (a grid for example) of the current selected page changed so that the grid can update accordingly. These logic could be written inside directive controller to be reused. When using together with isolate scope, this scope is not tight to application controller'scope and it's easy for you to configure pageSize to bind to any property of the application controller's scope.

这篇关于Angular ngController 与在指令中构建的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆