UPDATE
When working with strings in ngRepeat
instead of objects, there is no place to set a flag within your data elements. In such cases, it is recommended to use a custom directive. Contrary to Darryl Snow's opinion that a directive is unnecessary in this scenario, using a directive can actually improve performance by evaluating the parameter
once rather than in every $digest
cycle. Additionally, by implementing the functionality in a directive, you can easily reuse it in other templates without redundantly copying the expression. Below is an example of how such a directive could be structured:
.directive('parameter', function() {
return {
link: function($scope, $element, $attrs) {
$attrs.$observe('parameter', function(parameter) {
if (parameter.indexOf('TEST') == -1) {
$element.hide();
} else {
$element.text(parameter);
$element.show();
}
});
}
}
});
Template:
<div parameter="{{parameter}}"></div>
This directive reduces the number of watchers per parameter compared to your original solution, leading to better performance. However, it does disable two-way binding, meaning that if you need to edit the parameter
string dynamically, this approach may not be suitable.
ORIGINAL ANSWER
While it may technically work, the approach you proposed has some drawbacks:
Performance. Each time the $digest
loop runs, which can happen frequently depending on the interactivity of the application, the expression parameter.indexOf('TEST') != -1
needs to be evaluated. This can lead to multiple calls of .indexOf
after each interaction, impacting performance. A more efficient approach would be to perform this check once in the Controller and set a flag accordingly, for example:
$scope.showParameter = parameter.indexOf('TEST') != -1
In the template, you would then use:
<div ng-show="showParameter">{{parameter}}</div>
Model logic in template. It's debatable whether the decision of when the parameter should be visible belongs in the template. Ideally, this logic should reside in the Controller or Model to maintain separation of concerns and prevent the view layer from making assumptions about the model's behavior.