Robert
Robert

Reputation: 21

Context menu in angular js repeaters

I have a project where the client is insistent on a right click menu. The problem is that the function called from the options in the right click menu needs to have access to information on the model. Here is an example fiddle http://jsfiddle.net/7yCwW/1/ $scope.junkDataSet = [{index:foo, color:bar}] . Basically what I would need is a context menu with an option to show color. Once "show color" is clicked an alert that says the color of the item that was right clicked.

Upvotes: 2

Views: 4661

Answers (1)

goosemanjack
goosemanjack

Reputation: 950

Original answer

You could bind the relevant data as proprietary attributes inside the element and have the receiving function pull the attribute value out with el.getAttribute('mycolor');

http://jsfiddle.net/7yCwW/3/

<div ng-controller="Ctrl">
    <div ng-repeat="junk in junkDataSet" onclick="fooClick(event)" mycolor="{{junk.color}}" class="contextmenu">right click here</div>
</div>

<div id="myoutput" ></div>

...

function fooClick(e){
   var e = e || window.event
   var t = e.target;
    var clr = t.getAttribute("mycolor")
    var el = document.getElementById('myoutput');
    el.innerHTML = "You picked " + clr;
    el.style.background = clr;
    if(clr == 'black' || clr == "blue'){
        el.style.color = "white";
    }
    else{
        el.style.color = "black";
    }
}

Edit I played around with passing a full object reference and using an ng-click directive. You can use

<div ng-repeat="{{junk in junkDataSet}}" onclick='fooClick({{junk}})' > ... </div>
// in JSFiddle becomes invalid markup, but is actually OK
<div onclick="{ "index" : 0, "color" : "red" }" > ... </div>

Using ng-click is a no-go because on a context menu you have to return false to keep the default browser right click action from happening. That currently can't be achieved with the ng-click directive b/c it resolves to a controller method and the return statement confuses that operation.

I played around with ng-contextmenu, but that event handler feature doesn't exist. It's easy to add to Angular, but not part of the core offering

Where does that leave you? Either with the original answer (bind the data into a special attribute), or you could maintain some cached reference in a JS variable to the full list and bind just a key in some attribute. Or pass the key in as a parameter to your function. Not elegant, but you can't have everything in a v1 framework :)

Upvotes: 2

Related Questions