我已经找到了一些答案--试过了,但是没有一个适合我。
我有下面的div,其中我使用属性equalizer
<div class="text-center" equalizer='group'>
但是,如果窗口宽度> 400,我只希望该属性equalizer存在。
因此,我还在控制器中使用了以下代码:
$scope.windowWidth = $window.innerWidth;
$window.onresize = function(event) {
$timeout(function() {
$scope.windowWidth = $window.innerWidth;
});
};现在我明白了,我可以做这样的事情:
equalizer="{{ windowWidth>400 ? 'group' : ''}}"
然而,问题在于我是否在equalizer中有一个值,它仍然被应用-即<div class="text-center" equalizer=''>工作在与<div class="text-center" equalizer='group'>相同的位置。
那么,如何完全控制是否插入该属性呢?
要添加唯一的解决方案,我只有复制代码和使用ng-if
因此:
<div ng-if="windowWidth<400" class="text-centre">
和
<div ng-if="windowWidth>=400" class="text-center" equalizer='group'>
谢谢。
发布于 2016-07-03 19:32:32
我将创建一个resize指令,它正在更新一个范围变量,您可以在均衡器指令中检查该变量。
我不太确定您的均衡器指令在做什么,但是下面的演示(或者在这个小提琴中)应该能工作。
在演示中,我将删除均衡器指令,以测试是否使用该指令删除了调整大小事件。
添加指令看起来像下面未测试的代码,但是我会像在使用ng-if的演示中那样做
var childScope = $scope.$new();
var directiveElement = angular.element('<equalizer></equalizer>');
$document.append($compile(directiveElement)(childScope));(这里是谷歌提供的一个动态添加指令的演示。)
angular.module('demoApp', [])
.controller('mainController', function($scope) {
$scope.equalizerOptions = {
group: true
};
$scope.removeEqualizer = function() {
// just for testing if resize handler is removed
var equalizer = angular.element(document).find('equalizer');
//console.log(angular.element(document).find('equalizer').scope());
equalizer.scope().$destroy();
equalizer.remove();
}
})
.directive('equalizer', equalizerDir)
.directive('resize', resizeDir);
function resizeDir($window) {
return {
link: function(scope, element, attrs) {
scope.window = {};
function onResize(event) {
//console.log('Resized', scope, element, event);
scope.window.width = $window.innerWidth;
}
$window.onresize = function(evt) {
//console.log('Resize');
scope.$apply(onResize);
};
onResize(); //initial call
scope.$on('$destroy', function() {
//console.log('destroy dir');
$window.onresize = undefined;
});
}
};
}
function equalizerDir($timeout) {
return {
scope: {
options: '=',
width: '@'
},
template: '<div ng-if="width >= 400"><h2>equalizer with ng-if & resize dir</h2>' +
'<p>{{options.group ? \'grouped\': \'not grouped\'}}</p></div>',
link: function(scope, element, attrs) {
/*scope.$watchCollection('options', function() {
// would work but watch with ternary operator directly in markup is easier
scope.text = scope.options.group ? 'grouped': 'not grouped';
});*/
}
};
}<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>
<div ng-app="demoApp" ng-controller="mainController">
window width debugging: {{window.width}}
<equalizer options="equalizerOptions" width="{{window.width}}" resize>
</equalizer>
<button ng-click="equalizerOptions.group = !equalizerOptions.group">
toggle group
</button>
<button ng-click="removeEqualizer()">
remove equalizer (test unbinding resize)
</button>
</div>
https://stackoverflow.com/questions/38164774
复制相似问题