Reputation: 52611
I'm trying to write a directive that toggles classes based on a selector condition:
<label class-when="{'is-checked': ':has(input:checked)', 'is-disabled': ':has(input:disabled)'}">
<input type="checkbox">
Example checkbox
</label>
I need to somehow watch for DOM changes on the element and its descendents but I'm getting an ng:areq
error. How can I do this?
define(function (require) {
var _ = require('lodash');
return {
restrict: 'A',
scope: {
object: '@classWhen'
},
link: function (scope, element) {
scope.$watchCollection(function() {
return element.find('*').add(element);
}, function () {
_.forOwn(scope.object, function (test, classes) {
test = typeof test === 'boolean' ? test : element.is(test);
element.toggleClass(classes, test);
});
});
}
};
});
Upvotes: 12
Views: 297
Reputation: 12022
I have created a generic fiddle for this and also with RequireJS as you used.
Please have a look here
http://fiddle.jshell.net/balasuar/dugmu/15/
Note: Whatever property you added in the selector like :checked
and :disabled
, add the related angular property to the child element like ng-model
and ng-disabled
. It will work like a charm !!
Code
var app = window.app = angular.module("myApp", []);
define('classWhenDirective', function () {
//var _ = require('lodash');
var app = window.app;debugger;
app.directive("classWhen", function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(getChanges, setClasses)
function getChanges() {
var attrs = [];
function getAttrs(elm) {
$.each(elm.attributes, function(i, attrib){
var name = attrib.name;
var value = attrib.value;
if(value && name.indexOf('ng-') > -1) {
value = scope.$eval(value);
}
if(value) {
attrs.push(name + ':' + value);
}
});
}
getAttrs(element.get(0));
element.children().each(function(){
getAttrs(this);
});
return attrs.join(',');
}
function setClasses() {
var rawClasses = scope.$eval(attrs.classWhen);
Object.keys(rawClasses).forEach(function(className){
var expr = rawClasses[className]
var setClass = typeof expr === 'string'
? element.is(expr)
: !!expr;
element.toggleClass(className, setClass);
});
}
}
};
});
});
define('todo', ['classWhenDirective'], function() {
var app = window.app;
app.controller('myController', function($scope) {
});
});
// angular bootstrap
require(['todo'], function() {
angular.bootstrap(document, ['myApp']);
});
.is-checked {
color: green;
}
.is-disabled {
color: gray;
}
<script src="http://requirejs.org/docs/release/2.0.6/minified/require.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h2>ClassWhen Directive</h2>
<div ng-controller="myController">
<label>
<input type="checkbox" ng-model="disableAll" />Disable All</label>
<br>
<br>
<label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
<input type="checkbox" ng-model="checkBox1" ng-disabled="disableAll">ClassWhen checkbox 1
</label>
<br>
<label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
<input type="checkbox" ng-model="checkBox2" ng-disabled="disableAll">ClassWhen checkbox 2
</label>
</div>
Upvotes: 0
Reputation: 1580
Here's my attempt to solve your problem in generic way: https://plnkr.co/edit/kVyJQClmQhF3FeBTmKaX?p=preview
Directive code:
app.directive('classWhen', () => (scope, element, attrs) => {
scope.$watchCollection(getClasses, setClasses)
function getClasses() {
// We have to evaluate expression in attrs.classWhen so that we get object
const rawClasses = scope.$eval(attrs.classWhen)
const classes = {}
// then we normalize it so that strings are treated as jquery selectors
Object.keys(rawClasses).forEach((className) => {
const expr = rawClasses[className]
classes[className] = typeof expr === 'string'
? element.is(expr)
: !!expr // we normalize falsy values to booleans
})
// then we return it to $watchCollection
return classes
}
/**
* will be called whenever any of the classes changes
*/
function setClasses(classes) {
Object.keys(classes).forEach((className) => {
element.toggleClass(className, classes[className])
})
}
})
Upvotes: 1
Reputation: 11136
Okay, after reading your bounty comment, I understand that you want this to be controller independent. I spent some time completely reworking my solution, and I think I have finally figured out a way to accomplish what you want.
It really comes down to 2 things:
1) Detecting a change on the checkbox :checked
status, and
2) Detecting a change on the checkbox :disabled
status
Detecting 1)
was easy, as you can use a simple jQuery change handler, but detecting 2)
took a bit more research. It requires the use of scope.$watch
on the child ng-disabled
attribute.
Here is a demo of how this would work:
var app = angular.module("myApp", [])
.directive("classWhen", function() {
function setClasses(classWhen, $element, $input) {
Object.keys(classWhen).forEach(function(key) {
var test = classWhen[key];
// .toggleClass("className", true) === .addClass("className")
// .toggleClass("className", false) === .removeClass("className")
$element.toggleClass(key, $element.is(test));
});
}
return {
restrict: 'A',
link: function link (scope, element, attrs) {
var classWhen = JSON.parse(attrs.classWhen);
var $element = $(element);
$element.find("*").each(function (index, elem) {
var $elem = $(this);
// namespace the change event so we can easily .off() it
$elem.off("change.classWhen");
$elem.on("change.classWhen", function () {
setClasses(classWhen, $element, $elem);
});
// watch child ng-disabled attribute
scope.$watch($elem.attr("ng-disabled"), function (val) {
setClasses(classWhen, $element, $elem);
});
});
}
};
});
.is-checked {
background-color: yellow;
}
.is-disabled {
background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<label>
<input type="checkbox" ng-model="disableAll" />Disable All</label>
<br>
<br>
<label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
<input type="checkbox" ng-disabled="disableAll">Example checkbox 1
</label>
<br>
<label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
<input type="checkbox" ng-disabled="disableAll">Example checkbox 2
</label>
<br>
<label class-when='{"is-checked": ":has(input:checked, .test)", "is-disabled": ":has(input:disabled)"}'>
<input type="text" ng-disabled="disableAll" ng-class="testingClass" ng-model="testingClass"/>
<br>
<input type="checkbox" ng-disabled="disableAll">
Example checkbox 3
</label>
<br>
<label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
<input type="checkbox" ng-disabled="disableAll">Example checkbox 4
</label>
</div>
Upvotes: 6