简体   繁体   English

从指令视图中调用控制器中的函数angularJS

[英]calling function in a controller from a directive view, angularJS

I am trying to use ng-click to call two functions, in the html for a directive. 我正在尝试使用ng-click调用html指令中的两个函数。 The first function, 'checkUrl', is in the directives controller, and is working fine. 第一个功能“ checkUrl”位于指令控制器中,并且工作正常。

The second function, 'findUrl', is in the main app controller, and is not being fired. 第二个功能“ findUrl”位于主应用程序控制器中,不会被触发。

HTML: HTML:

<div class="status" ng-click="checkUrl()">
    <b ng-click="checkUrl()">{{card.status}}</b>
</div>
<div ng-click="findUrl()" class="image">
    <img ng-src={{card.image}} alt="">
</div>

I have a couple of questions: 我有一些问题:

1) Is this because the two controllers have different scopes, and one can't access the other? 1)这是因为两个控制器具有不同的作用域,而一个控制器无法访问另一个控制器吗?

2) How can I get the directives view/html to invoke the main controllers function? 2)如何获取指令view / html来调用主控制器功能?

directive's controller: 指令的控制器:

$scope.checkUrl = function() {
    console.log("invoking checkUrl from the directive's controller.")
    asnService.showUrl();
};

application controller: 应用控制器:

$scope.findUrl = function() {
    console.log("invoking findUrl from the app controller");
    asnService.showUrl();
};

To answer your question, you can use $scope.$parent.findUrl() to access the scope variables on the parent scope of your directive. 要回答您的问题,可以使用$ scope。$ parent.findUrl()访问指令父级作用域上的作用域变量。 Not necessarily recommended, but it works. 不一定推荐,但可以。

Here is 3 ways: 这是3种方式:

First 第一

if have not isolated scope in directive your example works fine https://jsfiddle.net/vorant/waf8rta2/1/ 如果指令中没有隔离范围,则您的示例可以正常工作https://jsfiddle.net/vorant/waf8rta2/1/

Second 第二

if scope in your directive isolated, add this code in directive's controller 如果指令中的作用域被隔离,则将此代码添加到指令的控制器中

    $scope.findUrl = function() {
        $scope.$parent.findUrl();
    };

https://jsfiddle.net/vorant/waf8rta2/2/ https://jsfiddle.net/vorant/waf8rta2/2/

Best way use $emit (directive have to has isolated scope) 最佳方式使用$emit (指令必须具有隔离范围)

directive's controller: 指令的控制器:

    $scope.findUrl = function() {
        $scope.$emit('status:findUrl');
    };

application controller: 应用控制器:

    $scope.$on('status:findUrl',function(){
        $scope.findUrl();
    });

https://jsfiddle.net/vorant/waf8rta2/4/ https://jsfiddle.net/vorant/waf8rta2/4/

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

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