我有一个定义的指令,如下所示:
angular.module('some-module').directive('someDirective', function() {
return {
restrict: 'E',
replace: 'true',
templateUrl: 'some-template.html',
link: link,
require: '^form',
transclude: true,
scope: {
decorate: '=',
}
};
});
让我们说这就是some-template.html的外观(实际模板中有更多内容):
<div ng-transclude></div>
这就是我将如何使用该指令:
<some-directive decorate="true">
<input name="x" type="number" ng-model="x">
<input name="y" type="number" ng-model="y">
</some-directive>
<some-directive decorate="false">
<input name="a" type="number" ng-model="a">
<input name="b" type="number" ng-model="b">
</some-directive>
我希望指令要做的是操纵DOM,这样如果decorate
为true
,那么两个输入字段应该用一些div
s进行修饰,如下所示: / p>
<div class="some-outer-class">
<div class="some-class-1">
<input name="x" type="number" ng-model="x">
</div>
<div class="some-class-2">
<input name="y" type="number" ng-model="y">
</div>
<div><i class="some-glyph-icon"></i></div>
</div>
如果decorate
属性为false或缺席,则该指令不应进行任何操作。
无法弄清楚如何做到这一点。任何帮助表示赞赏。
答案 0 :(得分:2)
答案 1 :(得分:-1)
您可以在指令中执行此操作。首先在指令中定义控制器,如下所示:
angular.module('some-module').directive('someDirective', function() {
var controller = function($scope) {
//The controller methods
};
return {
restrict: 'E',
replace: 'true',
templateUrl: 'some-template.html',
link: link,
require: '^form',
transclude: true,
scope: {
decorate: '=',
},
controller: controller,
controllerAs: 'myCtrl'
};
});
在控制器内部,检查decorate值,并相应地进行DOM操作。您可以通过$ scope访问控制器的decorate值。
var controller = function($scope) {
if($scope.decorate){
//Make the DOM manipulation
}
};
DOM操作如下:
var initialInput = document.querySelector('query'); //You have to select your desired input elements here
var decoratedInput = document.createElement("div");
decoratedInput.className += " some-class-1";
decoratedInput.innerHTML = "<input name='x' type='number' ng-model='x'>";
initialInput.parentNode.replaceChild(decoratedInput, initialInput);