I am looking to develop an attribute directive for ionItem that will monitor its own value:
<ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">….</ion-item>
I am facing challenges in creating the correct watch statement within the directive. The watch function is only triggered once during the initial rendering of the view. Subsequently, it does not respond when data.watchedValue
undergoes changes.
An important aspect of this directive is that it is a child of the ionItem
directive.
I have experimented with different approaches (refer to the comments in the source code of my-dir), but none of them seem to be effective.
Directive:
.directive('myDir', function() {
return {
restrict: 'A',
require: '^ionItem',
link: function(scope, element, attr, itemCtrl) {
console.log('my-dir initial value: ' + attr.myDir);
if (angular.isDefined(attr.myDir)) {
// scope.$watch("(" + attr.myDir + " === \"true\")", function(value) {
// scope.$watch('!!(' + attr.myDir + ')', function(value) {
scope.$watch(attr.myDir, function(value) {
console.log('my-dir watch new value: ' + value);
});
}
} // link
}; // return
}) // directive
Simplified usage of the directive:
<button class="button" ng-click="data.watchedValue = !data.watchedValue">
Change Value
</button>
<ion-content>
<ion-list>
<ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">
Item {{ item.id }}. Watched property: {{ data.watchedValue }}
</ion-item>
</ion-list>
</ion-content>
Code Pen featuring a complete example. Click on the Change Value
button to change the value.
Keep an eye on the console for any logs after the initial display.