javascript - 移动和桌面 View 的 Angular Controller 继承

标签 javascript angularjs mobile

我有一个应用程序,其中每个“组件”都有两个 View :移动 View 和桌面 View 。这些 View 非常相似,它们应该从同一个地方继承大量代码以保持 DRY,但又足够不同,它们应该都有自己的 Controller 。

为了解决这个问题,我有这样的设置:

观看次数

  • 基本模板“main.html”,使用 ng-include 显示“mainMobile.html”或“mainDesktop.html”
  • “mainMobile.html”为移动 View ,使用ng-controller指定移动 Controller
  • “mainDesktop.html”为移动 View ,使用ng-controller指定移动 Controller

Controller

  • 基本 Controller (MainCtrl)
  • 从基础继承并添加特定于移动设备的功能 (MainMobileCtrl) 的 Controller
  • 继承自 Base 并添加桌面特定功能 (MainDesktopCtrl) 的 Controller

以MainMobileCtrl为例。它继承自 MainCtrl,如下所示:

angular.module('app').controller('MainMobileCtrl', function ($scope, $controller) {
    var vm = this;
    angular.extend(vm, $controller('MainCtrl', { $scope: $scope }));
});

这将提取在 MainCtrl 的初始构造函数调用中设置的所有属性。一切都运行良好,直到我开始引入异步代码。

当基本 Controller (MainCtrl) 在 Promise 的解析中添加或更新属性时,这些更改不会推送到子 Controller (MainMobileCtrl):

angular.module('app').controller('MainCtrl', function ($scope, someService) {
    var vm = this;

    vm.notExposed = '---';

    someService.doThings().then(function () {
        vm.notExposed = 'unfortunately';
    });
});

angular.module('app').controller('MainMobileCtrl', function ($scope, $controller) {
    var vm = this;
    angular.extend(vm, $controller('MainCtrl', { $scope: $scope }));

    // just to illustrate that at this point, the service promise is resolved
    setTimeout(function () {
        console.log(vm.notExposed); // shows "---"
    }, 5000);
});

据我所知,这只是因为属性被复制到 MainMobileCtrl.vm 中一次,而没有任何引用。我应该提到,这似乎适用于 $scope,因为 $scope 看起来是通过引用共享的。但我想避免以这种方式使用 $scope ,因为它会导致 vm$scope 变量的困惑不匹配.

有什么体面的方法来完成我想做的事情吗?

最佳答案

如果你想在 Controller 之间共享数据,最好将这些数据存储在某个服务中,并将其注入(inject)到应该使用它的 Controller 中。 另外,如果你确实需要在这里实现 OOP 扩展,也许你应该这样做 it shown in this fiddle .

function extend(child, parent) {
    var F = function() { }
    F.prototype = parent.prototype;
    child.prototype = new F();
    child.prototype.constructor = child;
    child.superclass = parent.prototype;
}

function MainCtrl(){
   ...
}

extend(MainMblCtrl, MainCtrl);
function MainMblCtrl(){
   MainMblCtrl.superclass.constructor.apply(this, arguments);
   ...
}

否则您可以使用 EcmaScript 6 或 TypeScript,它们具有正常的类扩展。

关于javascript - 移动和桌面 View 的 Angular Controller 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990635/

相关文章:

javascript - 如何在canvas html中的多个图像上调用一个函数

angularjs - 如何根据 AngularJS 中的范围重定向到不同的模板?

AngularJS : TypeError: $http(. ..).success 不是 asp.net WebMethod 上的函数

javascript - 添加项目和 "refreshing"脚本来设置样式时,Jquery Mobile 复选框列表不会更新

jquery - Fullpage.js 和移动设备 : How to enable section/slide switch if content overflow must be enabled?

javascript - 如何使用 AngularJS 创建 5 颗评级星,其中第三颗被禁用

javascript - 如果显示两个 div(并且仅当它们都显示时)将文本向上推

javascript - 何时在 Angular JS 中使用发射和广播?

javascript - 如何在 Angular Material 和 Angular js中仅显示输入字段的最后四位数字?

javascript - 在移动设备中,哪个更快 : including an extra CSS file OR creating a style element in JavaScript?