AngularJS指令的两个实例,对2nd的更改会影响第一个实例。

时间:2015-09-28 21:12:42

标签: javascript angularjs directive

我有一个指令,在链接功能中将根据对其进行更改的时间更改图像缩略图。我在同一页面上有2个这个指令的实例。一个属于每个控制器,主控制器和编辑控制器。当我尝试在编辑状态(main的子节点)中更改属于指令实例的图像时,将更改为主状态中指令的第一个实例而不是第二个实例。任何帮助将不胜感激。

(function() {
'use strict';
/* @ngInject */

angular.module('MerchantPortalApp.directives.imageUpload', [])
    .directive('imageUpload', imageUpload);

function imageUpload($timeout) {
    return {
        restrict: 'EA',
        scope: {
            file: '=',
            img: '='
        },
        templateUrl: 'global/directives/imageUpload/imageUpload.html',
        link: function (scope, el, attrs) {

            var errorMsg = $(el.find('#error'));
            var fileInput = $(el.find('#fileInput'));
            var imageDisplayArea = $(el.find('#logoThumb')[0]);

            // Watch for user change on file input
            fileInput.change(function(e) {
                // Grab file from files array
                var file = fileInput.prop('files')[0];

                // REGEX to make sure file type is image
                var imageType = /image.*/;

                if (file.type.match(imageType)) {
                    // Create formData object and append the file object to it
                    var formData = new FormData();
                    formData.append('file', file, file.name);
                    scope.file = formData;

                    var reader = new FileReader();
                    // Remove any previous images from div
                    reader.onload = function(e) {
                        imageDisplayArea.prop('src', reader.result);
                    };
                    reader.readAsDataURL(file);
                } else {
                   errorMsg.show();
                }
                scope.$apply();
            });
        }
    };
}
})();

1 个答案:

答案 0 :(得分:0)

el.find('#error')清楚地表明您正在重复页面中的ID ....但ID根据定义必须是唯一的。

将所有重复的ID更改为类并相应地切换jQuery选择器:

el.find('.error')

此外,如果您的控制器正在共享绑定到scope.file in指令的数据服务,请确保2个控制器没有引用相同的服务对象