angularjsui.bootstrap

Binding ng-click argument object keys to scope properties?


I'm trying to pass an object with variable keys to an ng-click method. In regular javascript you would just do this:

var x = "fork";
var obj = {};
obj[x] = "three points" //{ fork: "three points" }

Normally to send objects via ng-click you would set up an object literal as the argument.

//in controller
$scope.val = "red";
//in view
<button ng-click="click( { item: val} )"></button> 
//output is { item: "red" }

But what if you want the key of the argument's object to be bound to a scope property?

//in controller
$scope.key = 29845;
//in view
<button ng-click="click( { {{key}}: 456 } )"></button>
//should output { 29845: 456 }

Trying this results in a syntax error. However, you can use this same syntax in ui.bootstrap typeahead's typeahead-on-select method and it works... I have no idea why though.

<input type="text"     
       typeahead="i for i in data"
       typeahead-on-select="select( { {{i}}: 'something' } )"
       class="typeahead" />

http://plnkr.co/edit/EfSvbP8fXBLoZhr8eWG5

How can you bind scope properties to object keys?


Solution

  • You can try something like this :

    <button ng-click="temp={};temp[key]=456;click(temp)"></button>
    

    See http://plnkr.co/edit/NfH3xNUXtBROiu9olHVE?p=preview.

    Though it will add temp variable in the scope.