[英]How can I apply a class from one directive to another in angularjs?
如何在不使用jQuery選擇器的情況下將類從toggleClass
指令添加到Header
指令? 不知道如何在AngularJS中做到這一點,在這種情況下是否需要對指令通信的指令?
<Header></Header>
<toggleClass></toggleClass>
在toggleClass指令中,我有:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
// add class to Header directive
}
}
}
};
及其模板:
<div ng-click="expandToggle()">
<span class="collapseText">Collapse</span>
<span class="expandText">Expand</span>
</div>
您可以將$emit
事件從toggleClass
指令更改為父控制器,並更改布爾值以控制添加/刪除類。
ToggleClass指令:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
scope.$emit('toggle');
}
}
}
};
父控制器:
angular
.module('yourModule')
.controller('YourController', ['$scope', YourController]);
function YourController($scope) {
$scope.$on('toggle', function() {
$scope.apllyNeededClass = true;
})
}
您的HTML:
<Header ng-class="{'classToApply': apllyNeededClass}"></Header>
<toggleClass></toggleClass>
您可以使用服務在控制器之間共享數據(在您的情況下為指令和控制器)。
ToggleClass指令:
module.exports = Directive;
function Directive(){
return {
restrict: 'E',
templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
link : function(scope, element){
scope.expandToggle = function() {
yourService.apllyNeededClass = true;
// don't forget to inject "yourService" in this directive
}
}
}
};
父控制器:
angular
.module('yourModule')
.controller('YourController', ['$scope', 'yourService', YourController]);
function YourController($scope, yourService) {
$scope.apllyNeededClass = yourService.apllyNeededClass;
// bind service variable to your $scope variable
}
您的HTML:
<Header ng-class="{'classToApply': apllyNeededClass}"></Header>
<toggleClass></toggleClass>
我只是在<Header>
標記上使用ng-class
,因為我不知道您的Header
指令的模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.