ng-model未在ng-if中更新

LG_*_*LG_ 3 angularjs

我无法在我的select html bloc中检索所选选项(ng-model = filter)的实际值.

请注意,如果我没有设置$ scope.filter,那么即使我在下拉列表中选择了一个选项,$ scope.filter也会保持未定义状态.

我的html模板,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>

在我的指令中:

      .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'
        }
    }])
Run Code Online (Sandbox Code Playgroud)

结果:

我可以看到实际值出现在我的html中,但我将始终在我的控制台中显示$ scope.filter.name的"语言",无论我选择哪个选项!我用截图给你看:http://hpics.li/4a37ae3

谢谢你的帮助.

[编辑:我做了一些测试,我的模型只有在它们不在" <div ng-if="..."></div>"] 内时才会被设置和更新.是否不允许将ng-if直接放入指令中?

答案:Angularjs ng-model在ng-if中不起作用

LG_*_*LG_ 9

我找到了解决方案,问题是ng-if创建了一个子范围.所以我将过滤器更改为$ parent.filter in

 <select ng-model="$parent.filter" ng-options="option.name for option in filterOptions" class="form-control">
      </select>
Run Code Online (Sandbox Code Playgroud)

  • “ ng-if创建了一个子范围”,这句话使我节省了工作时间 (2认同)