Javascript 如何使用指令设置其他指令?
我在控制器的作用域上有一个对象,其中包含输入的一些表示数据:Javascript 如何使用指令设置其他指令?,javascript,angularjs,Javascript,Angularjs,我在控制器的作用域上有一个对象,其中包含输入的一些表示数据: var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.settings = { value: 'xxx', required: true, show: true, readonly: false }; }); 在实际应用程序中,这是从服务器加载的较大对象的一部
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.settings = {
value: 'xxx',
required: true,
show: true,
readonly: false
};
});
在实际应用程序中,这是从服务器加载的较大对象的一部分。我创建了一个指令,将此演示对象作为输入,并附加必要的指令:
app.directive('fieldSettings',
[/*$injectables*/
function (/*$injectables*/) {
return {
priority: 100,
restrict: 'A',
scope: {
fieldSettings: '='
},
compile: function (el, attrs) {
return function (scope, iElement, iAttrs) {
iAttrs.$set('ng-model', 'fieldSettings.value');
iAttrs.$set('ng-show', 'fieldSettings.show');
iAttrs.$set('ng-required', 'fieldSettings.required');
iAttrs.$set('ng-readonly', 'fieldSettings.readonly');
}
}
};
}
]);
如图所示,添加了属性,但没有应用逻辑。根据angular的文档,我尝试应用的指令的优先级为0
,而input
指令的优先级为100
。我将我的设置为100
,但无论我为其选择了什么值,该值似乎都没有影响
我想要
<input field-settings="settings" />
举止
但实际上是
<input ng-model="fieldSettings.value" ng-show="fieldSettings.show" ng-required="fieldSettings.required" ng-readonly="fieldSettings.readonly" />
其中,
fieldSettings
是指令的局部作用域变量,绑定到MaintCtrl
的局部作用域变量settings
,只添加属性而不编译不会起任何作用
我的类似回答是:
是否有理由在
attrs.$set
上使用elm.attr
?哦tElm.removeAttr('field-settings')
是关键。我曾经尝试过$compile
,但是超过了最大调用堆栈大小
,这一点现在看起来很明显,因为它会尝试重新应用field settings指令,并陷入循环@ogc nick在这种情况下,他们的工作原理是一样的attrs.$set
的功能不仅仅是获取/设置属性。@ogc nick terminal&high priority对于这种自编译模式也非常重要。将优先级设置为100就足够了吗?100是输入的优先级,据我所知,我添加的指令的优先级为0。我以前没听说过终点站,不过我得查一下。我应该用它吗?
<input ng-model="fieldSettings.value" ng-show="fieldSettings.show" ng-required="fieldSettings.required" ng-readonly="fieldSettings.readonly" />
app.directive('fieldSettings',
['$compile',
function ($compile) {
return {
restrict: 'A',
scope: {
fieldSettings: '='
},
priority: 1001,
terminal: true,
compile: function(tElm,tAttrs){
tElm.removeAttr('field-settings')
tElm.attr('ng-model', 'fieldSettings.value');
tElm.attr('ng-show', 'fieldSettings.show');
tElm.attr('ng-required', 'fieldSettings.required');
tElm.attr('ng-readonly', 'fieldSettings.readonly');
var fn = $compile(tElm);
return function(scope){
fn(scope);
}
}
};
}