我正在创建一个自定义指令,根据屏幕大小将元素附加到DOM的特定部分。该功能应在$window.onresize
& $window.onload
我遇到的问题是在一个视图中多次触发相同的指令。
我迷路的地方是如何为页面上的每个元素编译指令。
HTML
<body ng-app="myApp">
<div ng-controller="myCtrl">
<div appendy appendy-from="#right1" appendy-to="#left1" appendy-breakpoint="768">
<h3>Should move Left1 to Right1 OR Right1 to Left1</h3>
</div>
<div appendy appendy-from="#right2" appendy-to="#left2" appendy-breakpoint="768">
<h3>Should move Left2 to Right2 OR Right2 to Left2</h3>
</div>
<div class="container">
<div class="row">
<div class="col-xs-6 text-center">
<h1>Left 1</h1>
<div id="left1"></div>
</div>
<div class="col-xs-6 text-center">
<h1>Right 1</h1>
<div id="right1"></div>
</div>
</div>
<div class="row">
<div class="col-xs-6 text-center">
<h1>Left 2</h1>
<div id="left2"></div>
</div>
<div class="col-xs-6 text-center">
<h1>Right 2</h1>
<div id="right2"></div>
</div>
</div>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', function ($scope) {}]);
app.directive('appendy', function ($window) {
return {
restirct: 'AE',
replace: 'false',
template: '',
link: function (scope, element, attributes) {
var appendy = function () {
scope.appendFrom = attributes["appendyFrom"];
scope.appendTo = attributes["appendyTo"];
scope.breakPoint = attributes["appendyBreakpoint"];
var appendFrom = angular.element(document.querySelector(scope.appendFrom));
var appendTo = angular.element(document.querySelector(scope.appendTo));
var breakPoint = scope.breakPoint;
var clientWidth = document.documentElement.clientWidth;
if (clientWidth < breakPoint) {
appendFrom.append(element);
} else {
appendTo.append(element);
}
};
$window.onresize = function () {
appendy();
};
$window.onload = function () {
appendy();
};
}
};
});
在查看其他代码时,appendy
函数应该附加到作用域,而不是在$窗口调整大小或加载时在元素上触发?
scope.appendy = function(){
//...
//...
}
element.($window).bind('resize, load', function(){
scope.appendy();
})
答案 0 :(得分:0)
不要将任何此类绑定到作用域,因为父作用域由两个实例继承并使用angular.element($window)
:
var appendy = function () {
var appendFrom = attributes["appendyFrom"];
var appendTo = attributes["appendyTo"];
var breakPoint = attributes["appendyBreakpoint"];
appendFrom = angular.element(document.querySelector(appendFrom));
appendTo = angular.element(document.querySelector(appendTo));
var clientWidth = document.documentElement.clientWidth;
if (clientWidth < breakPoint) {
appendFrom.append(element);
} else {
appendTo.append(element);
}
};
angular.element($window).bind('resize load', appendy);
}
的 DEMO 强>