gpt4 book ai didi

angularjs - 具有指令与服务的 DRYing Controller

转载 作者:行者123 更新时间:2023-12-01 23:42:45 25 4
gpt4 key购买 nike

我正在构建的应用程序有多个 View ,每个 View 都有自己的 Controller 。我所有的 Controller 都以相同的方式启动,并且在一种方法上有所不同;

$scope.a = ...              // same for all controllers
$scope.b = ... // same for all controllers
$scope.c = function(){...} // same for all controllers

$scope.d = function(){...} // is different for each controller

他们说让您的 Controller 保持精简,并通过服务分解它们。但是,如果我将 a、b、c 放入服务中,它们将在所有 Controller 之间共享,而我希望每个 Controller 在其自己的范围内保留自己的 a、b、c。 我不想分享数据,只是分享代码。

所以我创建了一个指令,它引用父作用域并在其自己的 Controller 中声明公共(public)内容。它解决了我的问题,但您是否可以推荐最佳做法?

最佳答案

如果您将 Controller 方法定义为作用域属性,那么您可以使用简单的混合方法来使用通用方法扩展每个作用域对象。

假设您定义了一个具有可重用方法的对象:

var mixin = {
a: function() { return this.name; },
b: function() {},
c: function() {}
};

然后当您需要这些方法时,您只需将它们混合到当前的 $scope 中:

app.controller('Controller1', function($scope) {

$scope.name = 'One';

// Create common methods
angular.extend($scope, mixin);

// Define unique method
$scope.d = function() {};
});

内部混合方法 this 将指向单独的 $scope 对象。

下面是该方法的演示。

演示: http://plnkr.co/edit/Vc00GsRTi5d6VNcILsva?p=preview

关于angularjs - 具有指令与服务的 DRYing Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com