Selects droplist inside ngTable loses its scope

北战南征 提交于 2019-12-13 04:35:07

问题


If I put the Selects (select.js) droplist inside ngTable, and try to show the selection from outside the table, it loses its scope and doesn't show the selection. Hopefully, I was able to explain this.

Here's the preview. In the preview, you will see a select droplist which has two output locations. One inside the table which works and another outside the table which doesn't.

http://plnkr.co/edit/tQYmRrTjXOhTohsESpNo?p=preview


回答1:


I solved your problem, and it had to do with levels of scope.

(First of all, why did you put the Select control within the table? They are not table data, so they don't go in the <table> tag.)

You were using a ngTable directive that created its own scope. So your Select was under two scopes, like so:

[DemoCtrl scope] -> [ngTable scope] -> [Select]

The selectedIcon is defined on the DemoCtrl scope.

You've run into a common problem. When the select looks for selectedIcon, it searches up the levels of inheritance and finds it. So it can read properties of parent/ancestor scopes. But it cannot write to them. Instead, your Select creates/changes the property on the ngTable scope, which is not seen by the binding outside it.

For this reason, AngularJS recommends that, instead of using values in ngModel, you reference objects. Because objects in Javascript are always by reference. So here's the fix:

Incorrect:

ng-model="selectedIcon"

Correct:

ng-model="obj.selectedIcon"

obj being an object you created on DemoCtrl scope.

The first few paragraphs explain this phenomenon well: https://github.com/angular/angular.js/wiki/Understanding-Scopes




回答2:


It works. Here's what I had to do. I had to modify the angular-strap.js. Add scope.$apply() to the following piece of code.

$select.update = function (matches) {
  scope.$matches = matches;
  if (controller.$modelValue && matches.length) {
    if (options.multiple && angular.isArray(controller.$modelValue)) {
      scope.$activeIndex = controller.$modelValue.map(function (value) {
        return $select.$getIndex(value);
      });
    } else {
      scope.$activeIndex = $select.$getIndex(controller.$modelValue);
    }
  } else if (scope.$activeIndex >= matches.length) {
    scope.$activeIndex = options.multiple ? [] : 0;
  }
  scope.$apply();
};


来源:https://stackoverflow.com/questions/21267823/selects-droplist-inside-ngtable-loses-its-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!