1个元素上的多个指令
鉴于我有以下两个指令。1个元素上的多个指令
1:Angular UI select - 此指令使用隔离范围。
2:myDirective - 在我的自定义指令,我也用隔离范围访问ngModel
我收到多个指令错误的值不能共享隔离范围。这就是我在我的指令中声明隔离范围的方式。
require: 'ngModel',
scope: {
modelValue: "=ngModel"
},
link: function (scope, el, attrs, ctrl) {
我用它像:
<ui-select myDirective multiple ng-model="GroupsModel" theme="select2" ng-disabled="disabled" style="width: 300px;" hidden-text-box ">
<ui-select-match placeholder="groups">{{$item}}</ui-select-match>
<ui-select-choices repeat="color in Groups ">
{{color}}
</ui-select-choices>
</ui-select>
我的问题是,我怎么能访问从我的自定义指令的ngmodel值,如果多个指令不能一起1元所使用的,是有围绕这一点的工作仍将保持约束力?
更新
我不能在我的指令下列功能访问所需的NG模型价值,如果我不使用空scope: {},
scope.reset = function() {
var modelValue =ctrl.$viewValue;
$timeout(function() {
el[0].focus();
}, 0, false);
};
这里是我的指令:
var app = angular.module('app');
app.directive('resetField', [
'$compile', '$timeout', '$http', function ($compile, $timeout, $http) {
return {
require: 'ngModel',
link: function (scope, el, attrs, ctrl) {
// compiled reset icon template
var template = $compile('<i ng-show="enabled" ng-mousedown="reset()" class="fa fa-floppy-o" style="padding-left:5px"></i>')(scope);
el.after(template);
scope.reset = function() {
var modelValue =ctrl.$viewValue;
$timeout(function() {
el[0].focus();
}, 0, false);
};
el.bind('input', function() {
scope.enabled = !ctrl.$isEmpty(el.val());
})
.bind('focus', function() {
scope.enabled = !ctrl.$isEmpty(el.val());
scope.$apply();
})
.bind('blur', function() {
scope.enabled = false;
scope.$apply();
});
}
};
}
]);
如果您仅使用隔离范围来获取select的ng模型,则可以不使用i过于宽泛的范围。
在链接功能只需使用scope[attrs.ngModel]
,你甚至可以把守着它(只要ngmodel是一个对象的属性ng-model=obj.prop1
)
您可以在一个元件上使用多个指令,这个问题是在应用在该指令
angular.directive('myDirective', [function(){
return {
scope: false,
require: 'ngModel',
link: function(scope, element, attr, ctrl){
scope.modelValue = ctrl.$viewValue;
}
}
}])
对不起还有另外一个我没有提到的情况。有时MyDirective没有使用多个指令。鉴于此,您的解决方案将工作? – joe
使用“要求”,以便能够访问另一个指令的控制器:一个元素上多个相互隔离的范围是无效的,可以使用require需要另一个指令在myDirective
。然后,您可以将该控制器注入指令实现的参数中。但是,如果您这样做,则不能使用隔离范围。
我用我的指令更新了我的问题,你可以看看 – joe