Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling href from dropdown in angularjs

I have the following drop down using angularjs.

   <select ng-href="#/edit/{{name.id}}" class="form-control"  id="{{name.id}}">  
   <option ng-repeat="name in addas | filter:cc"
   id="{{name.id}}" value="{{name.name}}">{{name.as_number}}</option>
  </select>

I am trying to call href on selected option in the drop down. The drop down populates fine. When I select any option it doesn't do anything or call the url. Please let me know how I can achieve this in angularjs.

like image 756
J. Davidson Avatar asked Jan 30 '14 18:01

J. Davidson


2 Answers

<select ng-model="adda" ng-options="a.name for a in addas" ng-change="onChange()">  
</select>

Sample controller:

function Ctrl($scope, $location) {
    $scope.addas = [
        {id: 1, name: 'a1', as_number: 1},
        {id: 2, name: 'a2', as_number: 2},
        {id: 3, name: 'a3', as_number: 3}
    ];

    $scope.onChange = function() {
        $location.path('/edit/' + $scope.adda.id);
    }
}

$location.path() does not seem to have any effect int the fiddle so instead the path is just displayed on the page but it should work as expected otherwise.


There is a number of things wrong with your approach. First of all you use ng-repeat on the option element so name.id won't be available outside of that element. It would probably be undefined when you use it in ng-href (unless you have it defined in the $parent scope as well but if I understand correctly this is not true).

like image 144
user2847643 Avatar answered Oct 21 '22 16:10

user2847643


The select statement looks a bit over complex to me and contains a few errors. Try this simpler version:

<select ng-model='adda'
        ng-options='as_number for name in addas' 
        ng-change='scrollToName()'>  
</select>

Controller:

$scope.scrollToName = function(){
    $location.hash($scope.adda.id);
    $anchorScroll()
};

Don't forget to inject $location and $anchorScroll into the controller.

like image 2
Gruff Bunny Avatar answered Oct 21 '22 15:10

Gruff Bunny