JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="app" ng-controller="MyCtrl as my">
<span my-array-viewer data-source="my.arr"></span>
<br/>
<span my-not-so-safe-array-viewer data-source="my.arr"></span>
<br /><hr />
<button ng-click="my.clearArray()">Clear!</button>
</div>
JavaScript
angular.module('app', [])
.controller('MyCtrl', function () {
this.arr = [1, 2, 3, 4, 5];
this.clearArray = function () {
this.arr = [];
}.bind(this);
})
.directive('myArrayViewer', function () {
return {
scope: {
arr: '=source'
},
link: function (scope, el, attrs) {
scope.$watch('arr', function (arr) {
if (angular.isArray(arr)) {
el.text('Your array have ' + arr.length + ' items');
} else {
el.text('You dont\'t have an array...');
}
});
}
}
})
.directive('myNotSoSafeArrayViewer', function ($parse) {
return {
link: function (scope, el, attrs) {
var arr = $parse(attrs.source)(scope);
if (angular.isArray(arr)) {
el.text('Your array have ' + arr.length + ' items');
} else {
el.text('You dont\'t have an array...');
}
}
}
});