定义 angular 个控制器和组件

Defining angular controllers and component

我试图从一个 angular 组件的控制器中调用一个函数到另一个组件的控制器。我找到了 答案,但控制器的定义与我遵循的教程中显示的不同,所以我对如何引用组件和模板感到困惑。

这是我目前如何根据官方 angular 教程定义我的控制器之一

angular.
  module('moduleName').
  component('firstComponent', {
    templateUrl: 'url/to/template',
    controller: function FirstController($scope) {  
       //I want to call a function in SecondController here
    }
  });

//in another component file
angular.
  module('moduleName').
  component('secondComponent', {
    templateUrl: 'url/to/template',
    controller: function SecondController($scope) {  
       //function here which will be called
    }
  });

假设我像上面链接的示例一样重新构建它们...

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

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);

//in another file 
var app= angular.module("myApp",[]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

我应该如何引用它们所属的每个控制器的组件,以及它们各自的模板?我试着像上面链接的例子那样写它们,但什么也没发生。我没有收到任何错误,但实际上什么也没发生。页面上没有显示任何内容。它试图写入控制台,但没有出现。

你的第二个代码块有正确的概念,但两个控制器都需要实例化才能工作。

这是一个有效的 JSFiddle。 https://jsfiddle.net/reid_horton/rctx6o1g/

当您单击按钮时,文本 Hello from callerComponent! 会出现在按钮下方。

HTML

<div ng-app="myApp">
  <caller-component></caller-component>
  <callee-component><</callee-component>
</div>

JS

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

app.component("callerComponent", {
    template: "<button ng-click='externalCall()'>Click Me!</button>",
    controller: function ($scope, $rootScope) {
        $scope.externalCall = function () {
            $rootScope.$emit("setText");
        }
    }
});

app.component("calleeComponent", {
    template: "<p>{{ myText }}</p>",
    controller: function ($scope, $rootScope) {
        $rootScope.$on("setText", function () {
            $scope.myText = "Hello from callerComponent!"
        });
    }
});