While working on my AngularJS filter, I encountered an issue with accessing the scope object in a specific area. After making some code changes, the problem was resolved, but I am unsure of what caused it. It seems like my understanding of scope and directives might be incorrect.
Within a directive, I attempted to access an array and use it in a scope watch function, but it wasn't functioning as expected.
The code that worked:
var currentScope = scope.mainList[scope.$index].list;
// This will trigger whenever any scope variable changes
scope.$watch(function() {
var hasTrue, hasFalse;
angular.forEach(currentScope, function(v) {
if (v["isSelected"]) {
hasTrue = true;
} else {
hasFalse = true;
}
});
if (hasTrue && hasFalse) {
iElement.attr('checked', false);
// iElement.addClass('greyed');
} else {
iElement.attr('checked', hasTrue);
// iElement.removeClass('greyed');
}
}, true);
The code that didn't work:
var currentScope = scope.mainList[scope.$index].list;
// This will only trigger when the corresponding scope variable changes
scope.$watch(currentScope, function(newVal) {
var hasTrue, hasFalse;
angular.forEach(newVal, function(v) {
if (v["isSelected"]) {
hasTrue = true;
} else {
hasFalse = true;
}
});
if (hasTrue && hasFalse) {
iElement.attr('checked', false);
// iElement.addClass('greyed');
} else {
iElement.attr('checked', hasTrue);
// iElement.removeClass('greyed');
}
}, true);
I require the second code snippet, but after altering variables, it is not registering the changes and appears as undefined.
Please refer to the following link for more insights: Code