Angularjs 使用组件或使用单独的控制器

Angularjs 使用组件或使用单独的控制器,angularjs,Angularjs,在Angular 1.5教程之后,他们将控制器包装在组件()中,如下所示 angular. module('myList'). component('myList', { templateUrl: 'template.html', controller: ['MyList', function MyController($scope){ var self = this; $scope.get({ id : '0' }).then

在Angular 1.5教程之后,他们将
控制器包装在
组件()中,如下所示

angular.
module('myList').
component('myList', {
  templateUrl: 'template.html',
  controller: ['MyList',
    function MyController($scope){
      var self = this;
      $scope.get({
        id : '0'
      }).then(function(response){
        return self.contents;
      })
    }
  ]
});
为了准备迁移到
Angular2
,将
控制器
放置在其自己的
js
文件中的最佳实践是什么
我应该遵循此示例,还是因为担心而将此代码分成两个文件?

注意:我刚刚意识到
component()
类是去年在
1.5
上推出的,在此版本之前,我一直被教程误导。

我建议: /*在mylist.controller.js中*/

   function MyController($scope){
     //your code
    }
现在在我的观点/组件中

declare var MyController:any;

@Component({
    selector: 'app-elem',
    templateUrl: 'test.html'
})

export class MyComponent {  
  new MyController(this)
}

这里有一些建议,

我建议您将您的实体保存在不同的文件中,即使是
模块
项目注册。让我解释一下这个简单的例子:

让我们想象一下,您有一个更大的模块,其中包含UI内容
模块('uiStuff')
。因此,我建议这样的结构:

UISTUF(文件夹)

  • uiStuff.module.js
  • uiStuff.service.js

    myList(文件夹)

    • myList.component.js
    • myList.controller.js
    • myList.partial.html
您的模块文件将始终包括仅注册角度实体-服务、组件、指令等。在未来,它将为您提供一些优势,因为在Angular2中不需要此代码,您将能够轻松地摆脱这些文件

示例uiStuff.module.js

angular.module('uiStuff')
  .service('someService', SomeService)
  .component('myList', myListComponent);
其中,
SomeService
-某个函数构造函数,
myListComponent
是组件对象。让我们看看下面的myList.component.js

var myListComponent = {
    bindings: {
       variable:'<'
    },
    templateUrl: 'myList.partial.html',
    controller: MyController
    // and all other component settings
}
var myListComponent={
绑定:{

变量:'您可以像使用构造函数一样使用它们,并在各自的类/组件中创建实例。@user32您是说在
控制器
文件中创建函数,然后从我的
组件
调用它们吗?这只是一个想法。没有理由像
导出类MyComponent{new MyController>这样奇怪的事情(这个)}
。组件类是控制器类。
$scope
不能用
这个
来代替。我试图做的是将类的上下文传递给控制器。有什么解决办法吗?为什么?
MyController
应该变成
MyComponent
。应该重构类以使用
这个
,而不是
$scope
对于作用域属性,这是A1组件的一个良好实践。对于作用域事件和观察者,无法摆脱
$scope
,这将是A1到A2迁移重构的主题。对。最好将控制器代码移到组件。