9

I'm trying to create a picker with Bootstrap Dropdown and AngularJS.

http://jsfiddle.net/qbjfQ/

<li ng-repeat="item in list"><a ng-click="current = item">Dynamic set {{item}}</a></li>

When I use ng-click statically in the list, it works fine (example 4 and 5) But when I use ng-click in ng-repeat, it won't update the value (example 1 to 3)

What can I do ?

3 Answers 3

27

It is a known problem with scoping in directives. You can read the article The Nuances of Scope Prototypal Inheritance to learn more about the scoping in angular js.

You need to change the ng-repeat to

<li ng-repeat="item in list">
  <a ng-click="$parent.current = item">
    Dynamic set {{item}}
  </a>
</li>

Demo: Fiddle

For explanation of the problem, you can read my answer to this question

Sign up to request clarification or add additional context in comments.

2 Comments

Or use the guideline: all scope references should contain a . (dot) <a ng-click='current.thing = item'>
The original fiddle rotted (because the angular-ui library path changed). Here is an updated Fiddle.
3

One option is to use a setter function within ng-click

HTML:

<li ng-repeat="item in list"><a ng-click="setCurrent( item)">Dynamic set {{item}}</a></li>

JS

function MyCtrl($scope) {

    $scope.list = [1,2,3];
    $scope.setCurrent=function(val){
         $scope.current =val;
    }    
    $scope.current = 0;    
}

DEMO: http://jsfiddle.net/qbjfQ/2/

Comments

1

There's an angularjs directive that does exactly that: https://gist.github.com/andyvr/5205764

Here's the jsfiddle with examples: http://jsfiddle.net/M32pj/1/

Sample: 
<select ng-model="example1" bs-selectbox>
 <option value="1">One</option>
 <option value="2">Two</option>
</select>

2 Comments

I'm trying to use this but how do I reload the directive. My options come from a remote source.
Please upgrade your source code in ordre to $compile your template. It doesn't work with AngularJS 1.2+. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.