【问题标题】:Parent isolated scope updated only once in Firefox父隔离范围在 Firefox 中仅更新一次
【发布时间】:2016-12-11 18:06:27
【问题描述】:

当在子自定义指令中触发 onchange 事件时,我正在尝试更新父范围变量。 我在子指令中使用的事件是input 文件,是由jqLit​​e 触发的onchange。这意味着, Angular 范围之外的操作。为了更新范围,我使用了scope.$evalAsync 函数(也尝试了$timeoutscope.$apply)。在父自定义指令中,我使用$watch 函数作为侦听器。

请查看jsfiddle 完整示例

标记

<div ng-app='myApp'>
  <parent></parent>
</div>

脚本

var myApp = angular.module('myApp', []);

myApp.directive('parent', function() {

  return {
    restrict: 'E',
    template: '<div class="parent">Parent' + '<span class="file-name">{{selectedFileName}}</span>' + '<child files="files"></child>' + '</div>',
    scope: {
      files: '='
    },
    link: function(scope){
        scope.$watch('files', function(newVal) {
        if (newVal && newVal.length > 0) {
          scope.selectedFileName = "selected file name: " + newVal[0].name;
        }
      });
    }
  };
});

myApp.directive('child', function() {

  return {
    restrict: 'E',
    template: '<div class="child">Child<br />' + '<span class="file-name">{{selectedFileName}}</span>' + '<file-upload files="files"></file-upload>' + '</div>',
    scope: {
      files: '='
    },
    link: function(scope) {
      scope.$watch('files', function(newVal) {
        if (newVal && newVal.length > 0) {
          scope.selectedFileName = "selected file name: " + newVal[0].name;
        }
      });
    }
  };
});

myApp.directive('fileUpload', function() {

  return {
    restrict: 'E',
    template: '<input type="file" />',
    scope: {
      files: '='
    },
    link: function(scope, element) {
      element.bind('change', function(e) {
        scope.$evalAsync(function() {
          scope.files = (e.srcElement || e.target).files;
        });
      });
    }
  };
});

在示例中,每次我选择新文件时,父范围变量files 都会完美更新,并调用其$watch 函数。

问题是在 Firefox 中父作用域 $watch 函数只被调用一次。仅限第一次。

提前致谢

【问题讨论】:

    标签: angularjs firefox angularjs-directive scope watch


    【解决方案1】:

    已解决。

    感谢post,它指出问题在于我正在使用$watch

    根据下面的解释:

    默认情况下,$watch 不检查对象是否相等,而只检查 参考

    就我而言,我正在观察一个数组。它的引用没有改变,这就是为什么没有调用 $watch 函数的原因。实际上发生了什么变化,它只是数组的内部属性。因此解决方案是改用$watchCollection(),即:

    Shallow 监视对象的属性并在任何时候触发 属性改变了……对于数组,这意味着观察数组项

    为什么$watch 不能在 Firefox 中运行,但在 Chrome 和 IE 中运行良好?答案是关于文件输入change 事件的实现。事实上,Firefox 总是触发 change 事件,即使在上传相同的文件时也是如此。这不是 Chrome 和 IE 中的行为。因此,Firefox 显然在每个 change 事件上保持相同的 files 数组对象,并且只更改其内部项目。 Chrome 和 IE 显然会在每个 change 事件上创建新的 files 对象,但在上传同名文件时不会触发该事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多