简体   繁体   中英

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. The first function, 'checkUrl', is in the directives controller, and is working fine.

The second function, 'findUrl', is in the main app controller, and is not being fired.

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?

2) How can I get the directives view/html to invoke the main controllers function?

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. Not necessarily recommended, but it works.

Here is 3 ways:

First

if have not isolated scope in directive your example works fine 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/

Best way use $emit (directive have to has isolated scope)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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