AleOtero93
AleOtero93

Reputation: 498

ng-click not calling my controller function

I've read lot of question with same text but none helped me, so I ask a new one.

I have a ng-app, ng-controller.

<div ng-app='mainApp'>
<div ng-init='period=".$_REQUEST['period']."' ng-controller='debtController'>

Then, some lines bellow, define them.

<script type='text/javascript'>
    var app = angular.module('mainApp', []);                               
        app.controller('debtController', function(){
            openDebt = function(period){
                console.log(period);
            }
    });
</script>

And last but not least, a ng-click that calls the function defined.

<a href="#" ng-click="openDebt('{{period}}')" />+</a>

So, if I click the '+' with the ng-click, nothing happens. But if I check the HTML there, and copy the text inside the ng-click, and then paste it in the console, it works. Why the function is not being called?

Anyone got any ideas?

Upvotes: 0

Views: 1056

Answers (3)

Sunil Lama
Sunil Lama

Reputation: 4539

Okay first embed the openDebt to scope inside the controller: $scope.openDebt. Second while in ng-click, you don't need handlebar to pass the value.

<script type='text/javascript'>
    var app = angular.module('mainApp', []);                               
        app.controller('debtController', function($scope){
           $scope.openDebt = function(period){
                console.log(period);
            }
    });
</script>

HTML:

<a href="#" ng-click="openDebt(period)" />+</a>

PLUNKER EXAMPLE: http://plnkr.co/edit/OyhBWkrREtt2JT2IWuVN?p=preview

Upvotes: 0

Best approach

Notice the assyntax. This create an alias for the controller

<div ng-init='period=".$_REQUEST['period']."' ng-controller='debtController as debt'>

change the ng-click asociated to controller alias

<a href="#" ng-click="debt.openDebt('period')" />+</a>

In the controller code using this for associate the controller with the html

var app = angular.module('mainApp', []);                               
        app.controller('debtController', function(){
            this.openDebt = function(period){
                console.log(period);
            }
    });

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222532

You can simply pass the variable without an expression

Change From:

<a href="#" ng-click="openDebt('{{period}}')" />+</a>

To:

<a href="#" ng-click="openDebt(period)" />+</a>

Upvotes: 1

Related Questions