I created a directive on Angular that receives 5 parameters and one of them is an optional array. The way I'm trying to deal with it is like follows:
app.directive('fooDirective', function() { return { restrict: 'AE', scope: { param1: '=', param2: '=' // optional array }, template: //... "<div ng-class='defineClass()'> Message </div>" //... controller: function($scope) { if (typeof $scope.param2 === 'undefined') $scope.param2 = []; console.log($scope.param2); $scope.defineClass = function() { if ($scope.param2.length == 0) return 'gray-text'; return 'red-text'; }; // ...... } } });
At some point in my code I check for the .length
of param2
and if it is undefined it throws a lot of errors. What is driving me nuts is that the console.log()
you can see there outputs a []
, indicating that the .length
of my param should be 0 and the errors on the console are shown after the output of the console.log().
So I guess I am missing something about either the way Angular binds the scopes or the flow that the directive is constructed. I have tried verifing my param on both link
and compile
phases and got the same problem.
So, what am I missing here? Thanks in advance.
Angular has an @Optional decorator, which when applied to a constructor argument instructs the Angular injector to inject null if the dependency is not found.
In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...
Parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. The DI framework provides null if the dependency is not found.
Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior. In summary, an attribute directive changes the appearance or behavior of a DOM element.
From the angular documentation (see the section for scope
bi-directional binding):
=
or=attr
- set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute.... If the parent scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You can avoid this behavior using=?
or=?attr
in order to flag the property as optional.
So the solution to make the parameter optional is to change the binding to be an optional two-way binding with the additional ?
.
... scope: { param1: '=', param2: '=?' // notice the ? makes this parameter optional. }, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With