简体   繁体   English

一个 AngularJS 控制器可以调用另一个吗?

[英]Can one AngularJS controller call another?

Is it possible to have one controller use another?是否可以让一个控制器使用另一个控制器?

For example:例如:

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.这个 HTML 文档只是在messageCtrl.js文件中打印由MessageCtrl控制器传递的MessageCtrl

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>

    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

The controller file contains the following code:控制器文件包含以下代码:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

Which simply prints the current date;它只是打印当前日期;

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl , how would one go about doing this?如果我要添加另一个控制器DateCtrl ,它将特定格式的日期交回MessageCtrl ,人们将如何去做? The DI framework seems to be concerned with XmlHttpRequests and accessing services. DI 框架似乎与XmlHttpRequests和访问服务有关。

There are multiple ways how to communicate between controllers.控制器之间有多种通信方式。

The best one is probably sharing a service:最好的可能是共享服务:

function FirstController(someDataService) 
{
  // use the data service, bind to template...
  // or call methods on someDataService to send a request to server
}

function SecondController(someDataService) 
{
  // has a reference to the same instance of the service
  // so if the service updates state for example, this controller knows about it
}

Another way is emitting an event on scope:另一种方法是在作用域上发出一个事件:

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

In both cases, you can communicate with any directive as well.在这两种情况下,您也可以与任何指令进行通信。

See this fiddle: http://jsfiddle.net/simpulton/XqDxG/看到这个小提琴: http : //jsfiddle.net/simpulton/XqDxG/

Also watch the following video: Communicating Between Controllers另请观看以下视频:控制器之间的通信

Html:网址:

<div ng-controller="ControllerZero">
  <input ng-model="message" >
  <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerOne">
  <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
  <input ng-model="message" >
</div>

javascript: javascript:

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };

  return sharedService;
});

function ControllerZero($scope, sharedService) {
  $scope.handleClick = function(msg) {
    sharedService.prepForBroadcast(msg);
  };

  $scope.$on('handleBroadcast', function() {
    $scope.message = sharedService.message;
  });        
}

function ControllerOne($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'ONE: ' + sharedService.message;
  });        
}

function ControllerTwo($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'TWO: ' + sharedService.message;
  });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];        

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];

If you want to call one controller into another there are four methods available如果您想将一个控制器调用到另一个控制器,有四种方法可用

  1. $rootScope.$emit() and $rootScope.$broadcast() $rootScope.$emit() 和 $rootScope.$broadcast()
  2. If Second controller is child ,you can use Parent child communication .如果第二个控制器是子控制器,则可以使用父子通信。
  3. Use Services使用服务
  4. Kind of hack - with the help of angular.element()一种 hack - 在 angular.element() 的帮助下

1. $rootScope.$emit() and $rootScope.$broadcast() 1. $rootScope.$emit() 和 $rootScope.$broadcast()

Controller and its scope can get destroyed, but the $rootScope remains across the application, that's why we are taking $rootScope because $rootScope is parent of all scopes .控制器及其作用域可能会被破坏,但 $rootScope 仍然存在于整个应用程序中,这就是我们采用 $rootScope 的原因,因为 $rootScope 是所有作用域的父级。

If you are performing communication from parent to child and even child wants to communicate with its siblings, you can use $broadcast如果您正在执行从父母到孩子的交流,甚至孩子也想与其兄弟姐妹交流,您可以使用 $broadcast

If you are performing communication from child to parent ,no siblings invovled then you can use $rootScope.$emit如果您正在执行从孩子到父母的通信,没有兄弟姐妹 invovled 那么您可以使用 $rootScope.$emit

HTML HTML

<body ng-app="myApp">
    <div ng-controller="ParentCtrl" class="ng-scope">
      // ParentCtrl
      <div ng-controller="Sibling1" class="ng-scope">
        // Sibling first controller
      </div>
      <div ng-controller="Sibling2" class="ng-scope">
        // Sibling Second controller
        <div ng-controller="Child" class="ng-scope">
          // Child controller
        </div>
      </div>
    </div>
</body>

Angularjs Code Angularjs 代码

 var app =  angular.module('myApp',[]);//We will use it throughout the example 
    app.controller('Child', function($rootScope) {
      $rootScope.$emit('childEmit', 'Child calling parent');
      $rootScope.$broadcast('siblingAndParent');
    });

app.controller('Sibling1', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling one');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('Sibling2', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling two');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('ParentCtrl', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside parent controller');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

In above code console of $emit 'childEmit' will not call inside child siblings and It will call inside only parent, where $broadcast get called inside siblings and parent as well.This is the place where performance come into a action.$emit is preferrable, if you are using child to parent communication because it skips some dirty checks.在上面的 $emit 'childEmit' 代码控制台不会调用内部子兄弟姐妹,它只会在父内部调用,其中 $broadcast 在兄弟姐妹和父内部也被调用。这是性能发挥作用的地方。 $emit 是更可取的是,如果您使用子级到父级的通信,因为它会跳过一些脏检查。

2. If Second controller is child, you can use Child Parent communication 2.如果Second controller是child,可以使用Child Parent通信

Its one of the best method, If you want to do child parent communication where child wants to communicate with immediate parent then it would not need any kind $broadcast or $emit but if you want to do communication from parent to child then you have to use either service or $broadcast它是最好的方法之一,如果你想在孩子想要与直接父母交流的情况下进行孩子父母的交流,那么它不需要任何类型的 $broadcast 或 $emit 但如果你想从父母到孩子进行交流,那么你必须使用 service 或 $broadcast

For example HTML:-例如 HTML:-

<div ng-controller="ParentCtrl">
 <div ng-controller="ChildCtrl">
 </div>
</div>

Angularjs Angularjs

 app.controller('ParentCtrl', function($scope) {
   $scope.value='Its parent';
      });
  app.controller('ChildCtrl', function($scope) {
   console.log($scope.value);
  });

Whenever you are using child to parent communication, Angularjs will search for a variable inside child, If it is not present inside then it will choose to see the values inside parent controller.每当您使用子级与父级通信时,Angularjs 都会在子级内部搜索变量,如果内部不存在该变量,则它将选择查看父级控制器内部的值。

3.Use Services 3.使用服务

AngularJS supports the concepts of "Seperation of Concerns" using services architecture. AngularJS 使用服务架构支持“关注点分离”的概念。 Services are javascript functions and are responsible to do a specific tasks only.This makes them an individual entity which is maintainable and testable .Services used to inject using Dependency Injection mecahnism of Angularjs.服务是 javascript 函数,只负责执行特定任务。这使它们成为可维护和可测试独立实体。服务用于使用 Angularjs 的依赖注入机制进行注入。

Angularjs code: Angularjs 代码:

app.service('communicate',function(){
  this.communicateValue='Hello';
});

app.controller('ParentCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Parent World");
});

app.controller('ChildCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Child World");
});

It will give output Hello Child World and Hello Parent World .它将给出输出 Hello Child World 和 Hello Parent World 。 According to Angular docs of services Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory .根据服务单例的Angular 文档- 依赖于服务的每个组件都获得对服务工厂生成的单个实例的引用

4.Kind of hack - with the help of angular.element() 4.Kind of hack - 在 angular.element() 的帮助下

This method gets scope() from the element by its Id / unique class.angular.element() method returns element and scope() gives $scope variable of another variable using $scope variable of one controller inside another is not a good practice.此方法通过元素的 Id / 唯一 class.angular.element() 方法从元素获取 scope() 方法返回元素,并且 scope() 使用另一个控制器内部的 $scope 变量给出另一个变量的 $scope 变量不是一个好习惯。

HTML:- HTML:-

<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
 <span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
 <div id='child' ng-controller='childCtrl'>{{varChild}}
   <span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
 </div>
</div>

Angularjs:- Angularjs:-

app.controller('ParentCtrl',function($scope){
 $scope.varParent="Hello Parent";
  $scope.getValueFromChild=function(){
  var childScope=angular.element('#child').scope();
  console.log(childScope.varChild);
  }
});

app.controller('ChildCtrl',function($scope){
 $scope.varChild="Hello Child";
  $scope.getValueFromParent=function(){
  var parentScope=angular.element('#parent').scope();
  console.log(parentScope.varParent);
  }
}); 

In above code controllers are showing their own value on Html and when you will click on text you will get values in console accordingly.If you click on parent controllers span, browser will console value of child and viceversa.在上面的代码中,控制器在 Html 上显示自己的值,当您单击文本时,您将在控制台中获得相应的值。如果您单击父控制器跨度,浏览器将控制子控制器的值,反之亦然。

Here is a one-page example of two controllers sharing service data:这是两个控制器共享服务数据的一页示例:

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="http://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
    return {
        thing : {
            x : 100
        }
    };
});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.thing; 
    $scope.name = "Second Controller!";
}
    </script>
</head>
<body>  
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
        <input ng-model="thing.x"/>         
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>
        <input ng-model="someThing.x"/>             
    </div>
</body>
</html>

Also here: https://gist.github.com/3595424也在这里: https : //gist.github.com/3595424

If you are looking to emit & broadcast events to share data or call functions across controllers , please look at this link : and check the answer by zbynour (answer with max votes).如果您希望发出和广播事件以在控制器之间共享数据或调用函数,请查看此链接:并检查zbynour的答案(以最大票数回答)。 I am quoting his answer !!!我引用他的回答!!!

If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:如果 firstCtrl 的作用域是 secondCtrl 作用域的父级,您的代码应该通过在 firstCtrl 中用 $broadcast 替换 $emit 来工作:

function firstCtrl($scope){
    $scope.$broadcast('someEvent', [1,2,3]);
}

function secondCtrl($scope){
    $scope.$on('someEvent', function(event, mass) {console.log(mass)});
}

In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (ie also secondCtrl).如果您的范围之间没有父子关系,您可以将 $rootScope 注入控制器并将事件广播到所有子范围(即也是 secondCtrl)。

function firstCtrl($rootScope){
    $rootScope.$broadcast('someEvent', [1,2,3]);
}

Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit.最后,当您需要将事件从子控制器分派到范围向上时,您可以使用 $scope.$emit。 If scope of firstCtrl is parent of the secondCtrl scope:如果 firstCtrl 的作用域是 secondCtrl 作用域的父级:

function firstCtrl($scope){
    $scope.$on('someEvent', function(event, data) { console.log(data); });
}

function secondCtrl($scope){
    $scope.$emit('someEvent', [1,2,3]);
}

Two more fiddles: (Non service approach)还有两个小提琴:(非服务方法)

1) For Parent- Child controller - Using $scope of parent controller to emit/broadcast events. 1) 对于父子控制器 - 使用父控制器的$scope来发出/广播事件。 http://jsfiddle.net/laan_sachin/jnj6y/ http://jsfiddle.net/laan_sachin/jnj6y/

2) Using $rootScope across non-related controllers. 2) 跨非相关控制器使用$rootScope http://jsfiddle.net/VxafF/ http://jsfiddle.net/VxafF/

Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.实际上使用发射和广播是低效的,因为事件在范围层次结构中上下冒泡,这很容易降低复杂应用程序的性能瓶颈。

I would suggest using a service.我建议使用服务。 Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419 .这是我最近在我的一个项目中实现它的方式 - https://gist.github.com/3384419

Basic idea - register a pub-sub/event bus as a service.基本思想 - 将发布订阅/事件总线注册为服务。 Then inject that event bus where ever you need to subscribe or publish events/topics.然后在需要订阅或发布事件/主题的地方注入该事件总线。

I also know of this way.我也知道这种方式。

angular.element($('#__userProfile')).scope().close();

But I don't use it too much, because I don't like to use jQuery selectors in angular code.但是我并没有过多使用它,因为我不喜欢在 angular 代码中使用 jQuery 选择器。

There is a method not dependent on services, $broadcast or $emit .有一种不依赖于服务的方法, $broadcast$emit It's not suitable in all cases, but if you have 2 related controllers that can be abstracted into directives, then you can use the require option in the directive definition.它并不适用于所有情况,但如果您有 2 个可以抽象为指令的相关控制器,那么您可以在指令定义中使用require选项。 This is most likely how ngModel and ngForm communicate.这很可能是 ngModel 和 ngForm 通信的方式。 You can use this to communicate between directive controllers that are either nested, or on the same element.您可以使用它在嵌套或同一元素上的指令控制器之间进行通信。

For a parent/child situation, the use would be as follows:对于父/子情况,用法如下:

<div parent-directive>
  <div inner-directive></div>
</div>

And the main points to get it working: On the parent directive, with the methods to be called, you should define them on this (not on $scope ):以及使其工作的要点:在父指令上,使用要调用的方法,您应该在this (而不是$scope )上定义它们:

controller: function($scope) {
  this.publicMethodOnParentDirective = function() {
    // Do something
  }
}

On the child directive definition, you can use the require option so the parent controller is passed to the link function (so you can then call functions on it from the scope of the child directive.在子指令定义上,您可以使用require选项,以便将父控制器传递给链接函数(因此您可以从子指令的scope调用其上的函数。

require: '^parentDirective',
template: '<span ng-click="onClick()">Click on this to call parent directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
  scope.onClick = function() {
    parentController.publicMethodOnParentDirective();
  }
}

The above can be seen at http://plnkr.co/edit/poeq460VmQER8Gl9w8Oz?p=preview以上可以在http://plnkr.co/edit/poeq460VmQER8Gl9w8Oz?p=preview看到

A sibling directive is used similarly, but both directives on the same element:同级指令的用法类似,但两个指令都在同一个元素上:

<div directive1 directive2>
</div>

Used by creating a method on directive1 :通过在directive1 1 上创建方法来使用:

controller: function($scope) {
  this.publicMethod = function() {
    // Do something
  }
}

And in directive2 this can be called by using the require option which results in the siblingController being passed to the link function:在指令 2 中,这可以通过使用require选项调用,这会导致兄弟控制器被传递给链接函数:

require: 'directive1',
template: '<span ng-click="onClick()">Click on this to call sibling directive1</span>',
link: function link(scope, iElement, iAttrs, siblingController) {
  scope.onClick = function() {
    siblingController.publicMethod();
  }
}

This can be seen at http://plnkr.co/edit/MUD2snf9zvadfnDXq85w?p=preview .这可以在http://plnkr.co/edit/MUD2snf9zvadfnDXq85w?p=preview上看到。

The uses of this?这个的用途?

  • Parent: Any case where child elements need to "register" themselves with a parent.父级:子元素需要向父级“注册”自己的任何情况。 Much like the relationship between ngModel and ngForm.很像 ngModel 和 ngForm 之间的关系。 These can add certain behaviour that can affects models.这些可以添加可能影响模型的某些行为。 You might have something purely DOM based as well, where a parent element needs to manage the positions of certain children, say to manage or react to scrolling.您可能也有一些纯粹基于 DOM 的东西,其中父元素需要管理某些子元素的位置,比如管理滚动或对滚动做出反应。

  • Sibling: allowing a directive to have its behaviour modified.兄弟:允许指令修改其行为。 ngModel is the classic case, to add parsers / validation to ngModel use on inputs. ngModel 是经典案例,将解析器/验证添加到 ngModel 对输入的使用。

I don't know if this is out of standards but if you have all of your controllers on the same file, then you can do something like this:我不知道这是否超出标准,但是如果您将所有控制器都放在同一个文件中,那么您可以执行以下操作:

app = angular.module('dashboardBuzzAdmin', ['ngResource', 'ui.bootstrap']);

var indicatorsCtrl;
var perdiosCtrl;
var finesCtrl;

app.controller('IndicatorsCtrl', ['$scope', '$http', function ($scope, $http) {
  indicatorsCtrl = this;
  this.updateCharts = function () {
    finesCtrl.updateChart();
    periodsCtrl.updateChart();
  };
}]);

app.controller('periodsCtrl', ['$scope', '$http', function ($scope, $http) {
  periodsCtrl = this;
  this.updateChart = function() {...}
}]);

app.controller('FinesCtrl', ['$scope', '$http', function ($scope, $http) {
  finesCtrl = this;
  this.updateChart = function() {...}
}]);

As you can see indicatorsCtrl is calling the updateChart funcions of the other both controllers when calling updateCharts.正如您所看到的,在调用 updateCharts 时,指标控件正在调用其他两个控制器的 updateChart 函数。

You can inject '$controller' service in your parent controller(MessageCtrl) and then instantiate/inject the child controller(DateCtrl) using:您可以在父控制器(MessageCtrl)中注入“$controller”服务,然后使用以下方法实例化/注入子控制器(DateCtrl):
$scope.childController = $controller('childController', { $scope: $scope.$new() });

Now you can access data from your child controller by calling its methods as it is a service.现在您可以通过调用其方法来访问来自您的子控制器的数据,因为它是一项服务。
Let me know if any issue.如果有任何问题,请告诉我。

Following is a publish-subscribe approach that is irrespective of Angular JS.以下是一种与 Angular JS 无关的publish-subscribe方法。

Search Param Controller搜索参数控制器

//Note: Multiple entities publish the same event
regionButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'region');
},

plantButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'plant');
},

Search Choices Controller搜索选择控制器

//Note: It subscribes for the 'onSearchParamSelectedEvent' published by the Search Param Controller
localSubscribe: function () {
        EM.on('onSearchParamSelectedEvent', this.loadChoicesView, this);

});


loadChoicesView: function (e) {

        //Get the entity name from eData attribute which was set in the event manager
        var entity = $(e.target).attr('eData');

        console.log(entity);

        currentSelectedEntity = entity;
        if (entity == 'region') {
            $('.getvalue').hide();
            this.loadRegionsView();
            this.collapseEntities();
        }
        else if (entity == 'plant') {
            $('.getvalue').hide();
            this.loadPlantsView();
            this.collapseEntities();
        }


});

Event Manager事件管理器

myBase.EventManager = {

    eventArray:new Array(),


    on: function(event, handler, exchangeId) {
        var idArray;
        if (this.eventArray[event] == null) {
            idArray = new Array();
        } else { 
            idArray = this.eventArray[event];
        }
        idArray.push(exchangeId);
        this.eventArray[event] = idArray;

        //Binding using jQuery
        $(exchangeId).bind(event, handler);
    },

    un: function(event, handler, exchangeId) {

        if (this.eventArray[event] != null) {
            var idArray = this.eventArray[event];
            idArray.pop(exchangeId);
            this.eventArray[event] = idArray;

            $(exchangeId).unbind(event, handler);
        }
    },

    fireEvent: function(event, info) {
        var ids = this.eventArray[event];

        for (idindex = 0; idindex < ids.length; idindex++) {
            if (ids[idindex]) {

                //Add attribute eData
                $(ids[idindex]).attr('eData', info);
                $(ids[idindex]).trigger(event);
            }
        }
    }
};

Global全球的

var EM = myBase.EventManager;

In angular 1.5 this can be accomplished by doing the following:在 angular 1.5 中,这可以通过执行以下操作来完成:

(function() {
  'use strict';

  angular
    .module('app')
    .component('parentComponent',{
      bindings: {},
      templateUrl: '/templates/products/product.html',
      controller: 'ProductCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductCtrl', ProductCtrl);

  function ProductCtrl() {
    var vm = this;
    vm.openAccordion = false;

    // Capture stuff from each of the product forms
    vm.productForms = [{}];

    vm.addNewForm = function() {
      vm.productForms.push({});
    }
  }

}());

This is the parent component.这是父组件。 In this I have created a function that pushes another object into my productForms array - note - this is just my example, this function can be anything really.在这里,我创建了一个函数,将另一个对象推送到我的productForms数组中——注意——这只是我的例子,这个函数可以是任何东西。

Now we can create another component that will make use of require :现在我们可以创建另一个使用require组件:

(function() {
  'use strict';

  angular
    .module('app')
    .component('childComponent', {
      bindings: {},
      require: {
        parent: '^parentComponent'
      },
      templateUrl: '/templates/products/product-form.html',
      controller: 'ProductFormCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductFormCtrl', ProductFormCtrl);

  function ProductFormCtrl() {
    var vm = this;

    // Initialization - make use of the parent controllers function
    vm.$onInit = function() {
      vm.addNewForm = vm.parent.addNewForm;
    };  
  }

}());

Here the child component is creating a reference to the parents component function addNewForm which can then be bound to the HTML and called like any other function.这里子组件正在创建对父组件函数addNewForm的引用,然后可以将其绑定到 HTML 并像任何其他函数一样调用。

You can use $controller service provided by AngularJS.您可以使用 AngularJS 提供的$controller服务。

angular.module('app',[]).controller('DateCtrl', ['$scope', function($scope){
  $scope.currentDate = function(){
    return "The current date is: " + new Date().toString(); 
  }
}]);

angular.module('app').controller('MessageCtrl', ['$scope', function($scope){

  angular.extend(this, $controller('DateCtrl', {
      $scope: $scope
  }));

  $scope.messageWithDate = function(message){
    return "'"+ message + "', " + $scope.currentDate;
  }

  $scope.action2 = function(){
    console.log('Overridden in ChildCtrl action2');
  }

}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM