如何角控制器(和范围)继承作品 [英] how angular controller (and scope) inheritance works

查看:87
本文介绍了如何角控制器(和范围)继承作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚控制器继承是如何工作的。我有三个控制器:

I'm trying to figure out how controller inheritance works. I have three controllers:

var myApp = angular.module('app', []);

myApp.controller('MainController', ['$scope', function($scope) {
    $scope.name = 'main';
    $scope.getName = function() {
        return $scope.name;
    };
}]);
myApp.controller('Child1', ['$scope', function($scope) {
    $scope.name = 'child1';
}]);
myApp.controller('Child2', ['$scope', function($scope) {
    $scope.name = 'child2';
}]);

和我的看法

<div ng-app='app'>
    <div ng-controller='MainController'>
        <div ng-bind='getName()'></div>

        <div ng-controller='Child1'>
            <div ng-bind='getName()'></div>

            <div ng-controller='Child2'>
                <div ng-bind='getName()'></div>
            </div>
        </div>
    </div>
</div>

但是他们都呈现主力。我该如何解决这个问题?

but they're all showing "main". How do I fix this?

这里有一个小提琴 http://jsfiddle.net/g3xzh4ov/3/

推荐答案

下面是一个例子如何控制器可在角延伸

myApp.service('baseCtrl', function () {
  this.name = 'base';
  this.getName = function() {
    return this.name;
  };
});

myApp.controller('MainController', ['baseCtrl', function (baseCtrl) {
  angular.extend(this, baseCtrl);
  this.name = 'main';
}]);
myApp.controller('Child1', ['baseCtrl', function (baseCtrl) {
  angular.extend(this, baseCtrl);
  this.name = 'child1';
}]);
myApp.controller('Child2', ['baseCtrl', function (baseCtrl) {
  angular.extend(this, baseCtrl);
  this.name = 'child2';
}]);

它要求使用 controllerAs ,它取代 $范围这个,它是这样的情况特别好。

It obliges to use controllerAs, which replaces $scope with this, it is especially good for such cases.

注意服务,而不是其他的角度服务类型的使用,它使用引擎盖下,所以这... 语句可以直接从控制器到单独的服务带来了。

Notice the usage of service instead of other Angular service types, it uses new under the hood, so this... statements can be brought right from a controller to separate service.

有做控制器继承的几种方法。这里是<一个href=\"http://stackoverflow.com/questions/31400979/instantiate-other-angularjs-controller-with-a-commoncontroller-when-using-iife/31439032#31439032\">another方法。

There are several ways of doing controller inheritance. Here is another approach.

对于原来的code,有角中没有控制器iheritance。和 $范围原型继承假定

Regarding the original code, there is no 'controller iheritance' in Angular. And $scope prototypical inheritance assumes that

$scope.getName = function() {
    return $scope.name;
};

你的情况

收益 $ scope.name 从那里它被定义的背景下, MainController 功能。

returns $scope.name from the context where it was defined, it is MainController function in your case.

这篇关于如何角控制器(和范围)继承作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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