【发布时间】:2014-05-31 17:42:17
【问题描述】:
我才刚刚开始使用 Angular,并且正在尝试正确使用指令。我正在编写一个自定义指令,该指令接受一个对象数组并将其解析为可变数量的垂直 div。它基本上是一个网格系统,其中元素排列成堆叠的垂直列而不是行。 div 的数量随着屏幕宽度动态变化,需要 div 类动态变化,并随着页面调整大小重构 div 列中数组元素的顺序。
当我将模板的内容用作纯静态 HTML 时,一切都加载得很好。当您使用输入字段等时,过滤器会动态更改数据集。
当我使用我的指令时,初始页面加载看起来不错。但是,动态过滤被破坏了 - 它不再绑定到输入字段。更重要的是,在页面调整大小时,HTML 根本无法编译,在 DOM 中留下空白屏幕和未编译的指令标签。
我不太了解 Angular,无法解决此问题。如果我不得不猜测,听起来好像由于范围问题,$compile 页面上的某些内容没有正确绑定。
注意:我知道为模板做字符串 concat 是不好的做法,但我只想在开始弄乱嵌套指令之前让事情正常工作。
编辑:这是我的前端代码的 Github 存储库链接:https://github.com/danheidel/education-video.net/tree/master/site
HTML
<body ng-controller="channelListController">
Creator: <input ng-model="query.creators">
Tags: <input ng-model="query.tags">
query: {{query}}
<div id="channel-view">
<channel-drawers channels="channels"></channel-drawers>
</div>
</body>
JS
.controller('channelListController', function ($scope, $http){
$http.get('api/v1/channels').success(function(data){
$scope.channels = data;
});
})
.directive('channelDrawers', function($window, $compile){
return{
restrict: 'E',
replace: true,
scope: {
channels: '='
},
controller: 'channelListController',
//templateUrl: 'drawer.html',
link: function(scope, element, attr){
scope.breakpoints = [
{width: 0, columns: 1},
{width: 510, columns: 2},
{width: 850, columns: 3},
{width: 1190, columns: 4},
{width: 1530, columns: 5}
];
angular.element($window).bind('resize', setWindowSize);
setWindowSize(); //call on init
function setWindowSize(){
scope.windowSize = $window.innerWidth;
console.log(scope.windowSize);
_.forEach(scope.breakpoints, function(point){
if(point.width <= scope.windowSize){
scope.columns = point.columns;
}
});
var tempHtml = '';
for(var rep=0;rep<scope.columns;rep++){
tempHtml +=
'<div class="cabinet' + scope.columns + '">' +
'<div class="drawer" ng-class="{' + ((rep%2 === 0)?'even: $even, odd: $odd':'even: $odd, odd:$even') + '}" ng-repeat="channel in channels | looseCreatorComparator : query.creators | looseTagComparator : query.tags | modulusFilter : ' + scope.columns + ' : ' + rep + '">' +
'<ng-include src="\'drawer.html\'"></ng-include>' +
'</div>' +
'</div>';
}
console.log(tempHtml);
element.html(tempHtml);
$compile(element.contents())(scope);
}
}
};
})
【问题讨论】:
-
有一个 jsFiddle 可以连接起来进行测试吗?
标签: angularjs angularjs-directive