Noitidart
Noitidart

Reputation: 37258

Creating button with ng-repeat that has an array with functions

I have an array of objects with two keys. Key label is for the text that will go on the button. And then action, which is a function I want to happen when a user clicks (ng-click) the button. When I do this, no error is thrown, however the function does not work :(

My js:

var myBtns = [{
    label: 'btn1',
    action: function() {
        alert('hi')
    }
}];

My html is inside a directive like this:

<button type="button" ng-repeat="aBtnInfo in myBtns" ng-click="aBtnInfo.action()">
     aBtnInfo.label
</button>

Here is a simple fiddle: http://jsfiddle.net/ppe34vLj/1/

On the other hand if I try <button ng-click="{{aBtnInfo.action}}">, it throws this error:

> "Error: [$parse:syntax] http://errors.angularjs.org/1.4.4/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7BaBtnInfo.action%7D%7D&p4=%7BaBtnInfo.action%7D%7D"

Of course in this situation my array is no longer a function a string:

var myBtns = [{
    label: 'btn1',
    action: '$scope.restore()'
}];

This simple fiddle shows this second case: http://jsfiddle.net/ppe34vLj/3/

Upvotes: 0

Views: 35

Answers (3)

Michael Buen
Michael Buen

Reputation: 39413

There's an error that the alert is sandboxed. If you really don't need an alert, try to use other mechanism for alert. Your code is working, just change alert to console.log, for example.

Live code: http://jsfiddle.net/b5fmqqen/

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, $window) {

    $scope.myBtns = [
        {
            label: 'btn1',
            action: function() { 
                console.log('hi') 
                $scope.something = "Yo";
            }
        }
    ];

}

Upvotes: 1

Aniket Sinha
Aniket Sinha

Reputation: 6031

Fixed your fiddle. Here's the updated fiddle.

You need to call the function using ()

<button ng-repeat="aBtn in myBtns" ng-click="aBtn.action()"> //() here
   {{aBtn.label}}
</button>

Your other code didn't work because you were passing the function as a string, i.e.

 $scope.myBtns = [
    {
        label: 'btn1',
        action: $scope.restoreDefaults() //pass function, not as '$scope.restoreDefaults()' which is a string
    }

Also, for this to work, your function definition should be before this chunk of code, otherwise JS won't register this function. Check this fiddle.

Upvotes: 1

Kevin Friedheim
Kevin Friedheim

Reputation: 324

Per my comment above:

https://jsbin.com/vunevazita/1/edit?html,js,output

remember that the view needs to reference the controller via $scope

Upvotes: 2

Related Questions