When checking for variables in AngularJS directives, remember to use camelCase instead of snake_case. For example, instead of $scope.my-option
, you should use $scope.myOption
.
CamelCased attributes should be referenced using camelCase in JavaScript source code as well.
Here is an example of how your HTML tag and AngularJS expression should look:
<my-directive my-option></my-directive>
{{ $scope.myOption ? 'YES' : 'NO' }}
In some cases, you may not even need to include the $scope
variable, simplifying the expression to:
{{ myOption ? 'YES' : 'NO' }}
If you prefer not to add the check as a watcher in your HTML code, you can utilize the link function of your directive. The AngularJS documentation provides more information on this topic.
Here is an example of how you can implement this in your directive:
angular
.module('myModule')
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {
myOption: '=?'
},
link: function(scope, element) {
if (scope.myOption) {
// You have the attribute
} else {
// You don't
}
}
}
});