javascript - 从 1.2.x 更新后,指令不从 Controller ($scope)链接

标签 javascript html angularjs angularjs-directive angularjs-scope

我制定了一个指令,通过将它们注入(inject)到独立的指令中来帮助我减少需要注入(inject)到主应用程序 Controller 中的依赖项的数量。

例如,我有一个性别下拉列表["MALE, "FEMALE"]。我已经将这个数组注册为一个值提供者。这是一个指令的简单示例,它在AngularJS 1.2.28

指令:

module.directive('appGenderOptions', ['genders', function(genders) {
  return {
    restrict: 'A',
    require: 'ngModel',
    controller: function($scope) {
      $scope.genders = genders;
    },
    compile: function(elem, attr) {
      attr.ngOptions = 'g for g in genders';
    }
  };
}]);

查看:

<select ng-model="person.gender" app-gender-options></select>

因此,当此指令被链接时,它会将性别添加到选择列表并绑定(bind)到模型,而无需将性别注入(inject)主 Controller 。

更新到最新版本 1.4.2 后,性别不再附加到选择列表中。我怀疑它与 1.3 中对 HTML 编译器 $compile 所做的重大更改有关,并且它们现在可以进行范围隔离,但不可否认我有点难过。

能否就如何修复此便利指令提供一些建议?

最佳答案

这是一个奇怪的问题,在审查 Migration docs 时,我无法获得足够的信息来了解更改的内容以指出可能破坏了您的 1.2 示例的内容。虽然我很想详细了解,但作为您问题的解决方法,以下内容应该可以为您解决...

注意我已经注入(inject)了 $compile 服务,您将在示例中看到

compile: function(elem, attr) {
    elem.removeAttr('app-gender-options'); // necessary to avoid infinite compile loop
    elem.attr('ng-options', 'g for g in genders');
    return function(scope) {
        $compile(elem)(scope);
    };
}

JSFiddle Link - 工作示例

关于javascript - 从 1.2.x 更新后,指令不从 Controller ($scope)链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507965/

相关文章:

javascript - jQuery 代码 : Starting from Parent to Child; not from Child to Parent

javascript - Angular 服务的多个实例

angularjs - 如何使用 Angular 将文本文件拖到文本区域以显示内容

javascript - 如何在 html 表格中给出分界线。?

javascript - 将 Summernote 与 Meteor 结合使用(发现 Meteor)

javascript - 如何限制对函数的调用?

javascript - Angular : how can I order ng-repeat by array order?

javascript - 单个 html 文件或 javascript 文件中有多少 document.ready?

javascript - CSS - 停止表格单元格背景溢出其宽度/高度之外

jquery - Bootstrap 轮播完全显示浏览器窗口的右侧