AngularJS控制器构造函数和带参数的实例化

时间:2013-12-10 11:16:26

标签: angularjs

是否可以在AngularJS中实例化控制器并将参数传递给其构造函数,就像在OOP中一样?我无法弄清楚如何重构3个相同的控制器只有变量名称和内容改变...

感谢名单。

2 个答案:

答案 0 :(得分:2)

如果页面上有3个单独的部分,它们具有非常相似的控制器代码,则听起来应该考虑使用指令。即使您不需要直接控制DOM(这是使用指令的经典原因),并且只需要标准的Angular数据绑定,那么这是通过设置的属性在不同的上下文中重用控制器的好方法指令。

你可以在

看到一个正常工作的傻瓜

http://plnkr.co/edit/qclp6MOxGWP7Ughod4T8?p=preview

但关键是指令可以绑定到父作用域控制器中的变量。比如,在父作用域中你有3个变量,所以:

$scope.myVariable1 = 'Value 1';
$scope.myVariable2 = 'Value 2';
$scope.myVariable3 = 'Value 3';

然后,您可以在模板中设置3个指令实例:

<my-directive my-param="myVariable1"></my-directive>
<my-directive my-param="myVariable2"></my-directive>
<my-directive my-param="myVariable3"></my-directive>

然后每个指令都可以使用'my-param'属性中的变量

scope: {
  'myParam':'='
}

'='表示在指令的范围内,你有一个名为'myParam'的变量,它等于(+绑定)指令上'my-param'属性指定的变量。因此,在指令的模板上,您可以使用:

<div>Value of parameter: {{myParam}}</div>

在指令的控制器中,您可以访问:

$scope.myParam

然后应该能够根据该实例的myParam自定义其行为。

答案 1 :(得分:-3)

您可以使用通用接口创建服务,然后通过依赖注入将相应的服务传递给每个控制器。在我的代码中,这是表控制器的情况,其中唯一改变的是数据源:

想象一下,你有一些看起来像这样的代码

angular.module('myapp').controller('TableACtrl', ['$scope', function($scope) {
    $scope.data = // get the data from some source
    $scope.someFunction = function () { ... };
    $scope.someOtherFunction = function () { ... };
}]);

angular.module('myapp').controller('TableBCtrl', ['$scope', function($scope) {
    $scope.data = // get the data from some other source
    $scope.someFunction = function () { ... };
    $scope.someOtherFunction = function () { ... };
}]);

它看起来像:

var tableCtrl = function($scope, dataSource) {
    $scope.data = dataSource.getData();
    $scope.someFunction = function () { ... };
    $scope.someOtherFunction = function () { ... };
};

angular.module('myapp')
    .controller('TableACtrl', ['$scope', 'dataSourceA', tableCtrl])
    .controller('TableBCtrl', ['$scope', 'dataSourceB', tableCtrl])

angular.module('myapp')
    .service('dataSourceA', function() {
       return {
           getData: function() { ... }
       };
    });
angular.module('myapp')
    .service('dataSourceB', function() {
       return {
           getData: function() { ... }
       };
    });

我仍然会把东西放在一个模块中,所以你不会污染全局窗口。但这是一个不同的问题。

相关问题