Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-model is not updated in ng-if

Tags:

angularjs

I'm failing to retrieve the actual value of my selected option (ng-model=filter) in my select html bloc.

Note that if I don't set $scope.filter then $scope.filter stay undefined even if I select an option in the dropdown list.

My html template, filters.html :

<div ng-if="!showFilterTemplatePlz"> <button class="btn btn-primary" ng-click="showFilterTemplate()" type="button">Add Filter</button> </div> <div ng-if="showFilterTemplatePlz" class="inline"> <button class="btn btn-primary" ng-click="closeFilters()" type="button">Close filters</button> <label>filters</label> <select ng-model="filter" ng-options="filter.name for filter in filterOptions" class="form-control"> </select> <p>{{filter.name}}</p> <button ng-click="addFilter()" id="addFilterButton" class="btn btn-primary btn-sm btn-default" type="button"><i class="fa fa-plus"></i> Add</button> </div>

In my directive:

      .directive('filters', ['retrieveStaticDatasService','usersService', function(datasService, usersService) {
        return {
            restrict: 'E',
            scope: false,
            controller: function ($scope) {
                /* init */
                $scope.filterOptions = [
                    {name: "languages"},
                    {name: "nationality"},
                    {name: "location"}
                ];
                $scope.filter = $scope.filterOptions[0];
                /* end init */
                $scope.showFilterTemplate = function(){
                      $scope.showFilterTemplatePlz=true;
                }
                $scope.closeFilters = function(){
                    $scope.showFilterTemplatePlz=false;
                }
                $scope.addFilter = function(){
                    console.log("filter to add : " + $scope.filter.name);                        
                }
            },
            templateUrl: '/partials/components/filters.html'
        }
    }])

Result :

I can see the actual value appears in my html but i will always show "languages" for$scope.filter.name in my console, whatever option I selected! I took a screenshot to show you : http://hpics.li/4a37ae3

Thanks for your help.

[Edit : I made some test and my model are setted and updated only if they are not inside the "<div ng-if="..."></div>"]. Is it not allowed to put a ng-if directly in the directive?

Answer : Angularjs ng-model doesn't work inside ng-if

like image 789
LG_ Avatar asked Dec 26 '22 12:12

LG_


1 Answers

I found the solution, the problem was that ng-if creates a child scope. So I changed filter to $parent.filter in

 <select ng-model="$parent.filter" ng-options="option.name for option in filterOptions" class="form-control">
      </select>
like image 90
LG_ Avatar answered Dec 28 '22 07:12

LG_