定义Angular控制器和组件

20 浏览
0 Comments

定义Angular控制器和组件

我试图在一个Angular组件的控制器中调用另一个组件的控制器中的函数。我在这里找到了一个解答,但是这个解答中的控制器定义方式与我所遵循的教程中的方式不同,所以我不知道如何引用这些组件和模板。

这是我目前如何根据官方的Angular教程定义其中一个控制器的方式:

angular.
  module('moduleName').
  component('firstComponent', {
    templateUrl: 'url/to/template',
    controller: function FirstController($scope) {  
       //我想在这里调用SecondController中的一个函数
    }
  });
//在另一个组件文件中
angular.
  module('moduleName').
  component('secondComponent', {
    templateUrl: 'url/to/template',
    controller: function SecondController($scope) {  
       //这里有一个将被调用的函数
    }
  });

如果我像上面链接的例子中那样重新组织它们...

var app= angular.module("myApp",[]);
app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });
        $scope.parentmethod = function() {
            //任务
        }
    }
]);
//在另一个文件中
var app= angular.module("myApp",[]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

我应该如何引用每个控制器所属的组件,以及它们各自的模板?我尝试按照我上面链接的例子的方式编写它们,但是什么都没有发生。我没有收到任何错误,但页面上什么都没有显示。我尝试将内容写入控制台,但是什么都没有出现。

0
0 Comments

原因:

在上述代码中,有两个Angular控制器(controllers),即callerComponent和calleeComponent。在callerComponent控制器中,当点击按钮时,通过$rootScope发出事件"setText",而在calleeComponent控制器中,通过$rootScope监听事件"setText",并在接收到事件后将myText属性的值设置为"Hello from callerComponent!"。然而,由于在HTML中没有实例化calleeComponent控制器,所以无法正常工作。

解决方法:

要解决这个问题,需要在HTML中实例化calleeComponent控制器,使其能够接收到事件并更新myText属性的值。以下是修改后的代码示例:

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!"
        });
    }
});

通过实例化calleeComponent控制器,我们可以使事件"setText"能够被正确接收并更新myText属性的值,从而达到预期的效果。

0