2016-08-23 108 views
0

我想从一个角度组件的控制器中调用一个功能到另一个组件的控制器。我发现this的答案,但控制器的定义与我在后续教程中显示的不同,所以我很困惑我应该如何引用组件和模板。定义角度控制器和组件

这里是我目前根据官方公布的角度教程定义我的控制器之一

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", {}); 
     } 
    } 
]); 

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

+0

可以添加你的HTML也? – Aravind

+0

此时确实没有HTML。我添加了一个警报函数来测试,以及控制台日志记录。当我使用控制台日志(在“重组”之前)消息显示。尝试重组后,什么都没有发生。我只是试图让控制器互相“交谈”......或者自己为此事 – user1852176

回答

1

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

这是一个可用的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!" 
     }); 
    } 
}); 
+0

谢谢,这工作。唯一让我困惑的是控制器的命名。由于没有明确声明,Angular是否假定控制器的名称与其组件相同? – user1852176

+0

控制器功能本身是匿名的,所以它没有名字。如果您需要从组件的模板访问控制器,则可以使用'controllerAs'属性。更多关于这里 - https://docs.angularjs.org/api/ng/service/$compile#-controlleras- –