How can you pass a bound variable to an ng-click function?

JavascriptAngularjs

Javascript Problem Overview


I have a simple delete button that will accept a string or number but won't accept an ng-model variable ( not sure if that's the correct terminology ).

<button class="btn btn-danger" ng-click="delete('{{submission.id}}')">delete</button>

Which generates:

<button class="btn btn-danger" ng-click="delete('503a9742d6df30dd77000001')">delete</button>

However, nothing happens when I click. If I hard code a variable then it works just fine. I assume I'm just not doing things the "Angular" way, but I'm not sure what that way is :)

Here's my controller code:

$scope.delete = function ( id ) {
    alert( 'delete ' + id );
}

Javascript Solutions


Solution 1 - Javascript

You don't need to use curly brackets ({{}}) in the ng-click, try this:

<button class="btn btn-danger" ng-click="delete(submission.id)">delete</button>

Solution 2 - Javascript

The ngClick directive binds an expression. It executes Angular code directly (as ngIf, ngChange, etc.) without the need of {{ }}.

angular.module('app', []).controller('MyCtrl', function($scope) { 
    $scope.submission = { id: 100 };

    $scope.delete = function(id) {
        alert(id + " deleted!");
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
    <button ng-click="delete(submission.id)">Delete</button>
</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionccraigView Question on Stackoverflow
Solution 1 - Javascriptpkozlowski.opensourceView Answer on Stackoverflow
Solution 2 - JavascriptMistalisView Answer on Stackoverflow