我在使用uib-modal中的自定义指令双向绑定时遇到了困难。 该指令从uib-modal范围获取模型变量,但在更改时,uib-modal中的模型不适用。
我console.log
范围并获得了仅使用$scope.$parent.$parent
访问uib-modal范围的指令...由于某种原因,双向绑定不起作用。
现在我使用指令模型属性执行eval()
:
link: function (scope, element, attrs, ctrls) {
scope.uibScopeModel = attrs.ngModel;
}
eval('$scope.$parent.$parent.' + $scope.uibScopeModel + ' = $scope.model');
它的工作但它似乎不是解决这个问题的好方法..
为什么双向绑定无法正常工作?它是uib-modal的已知问题吗?以及如何解决?
我的自定义指令:
angular.module('mean.upload').directive('uploadDirective', function (Upload) {
return {
restrict: 'E',
require: 'ngModel',
scope: {
model: '=ngModel', // the model
type: '@type', // type of upload (imageSingle/fileSingle)
required: '@required', //
fileTypeAccept: '@fileTypeAccept',
},
templateUrl: function (elem, attr) {
switch (attr.type) {
case 'imageSingle':
return '/upload/views/directive_templates/image-single.tpl.html';
case 'fileSingle':
return '/upload/views/directive_templates/file-single.tpl.html';
}
},
link: function (scope, element, attrs, ctrls) {
scope.uibScopeModel = attrs.ngModel;
},
controller: function ($scope, $rootScope) {
$scope.uploader = Upload.getDefaultUploader();
$scope.uploader.onCompleteItem = function (item, response, status, headers) {
if ($scope.type === 'imageSingle') {
$scope.model = Upload.uploadPath + response.filename;
} else if ($scope.type === 'fileSingle') {
$scope.model = {
src: Upload.uploadPath + response.filename,
name: item.file.name,
type: item.file.type
};
}
eval('$scope.$parent.$parent.' + $scope.uibScopeModel + ' = $scope.model');
}
}
}
});
标记:
<upload-directive
ng-model="file"
type="fileSingle"
file-type-accept="application/pdf">
</upload-directive>
指令模板:
<div nv-file-drop uploader="uploader">
<div class="well drop-zone" nv-file-over uploader="uploader">
<div class="row" ng-show="model">
<div class="uploaded-file-teaser col-sm-6 col-sm-offset-3 validation-icon-container">
<div class="teaser-edit-buttons">
<button class="btn btn-xs" ng-click="model=null">
<i class="fa fa-trash"></i>
</button>
</div>
<div class="file-container type-{{model.name | extension}}">
<p><i class="fa"></i></p>
<a href="{{model.src}}" target="_blank" title="{{model.name}}">
{{model.name | filename }}.{{model.name | extension}}
</a>
</div>
</div>
</div>
<p ng-show="!model">Drop file here</p>
<div nv-file-drop uploader="uploader" class="input-file-container">
<button class="btn btn-success btn-large">
<i class="fa fa-upload"></i> {{ buttonText || 'Upload File' }}
</button>
<input class="browse-image-btn" type="file" nv-file-select
input-validation-upload ng-model="model"
uploader="uploader" accept="{{fileTypeAccept}}"
required="required"/>
</div>
</div>
</div>
答案 0 :(得分:-1)
我在编写自己的指令时遇到了同样的行为。我的解决方案是根本不使用指令的范围,并用函数更新范围。
指令:
app.directive('sfTableHeader', function() {
return {
restrict: 'A',
scope: false,
template: '<div><a ng-click="updateScope(1234567)">click me</a></div>'
}
});
控制器:
$scope.updateScope = function(someNumber) {
$scope.number = someNumber;
};