Monday, 11 January 2016

AngularJS: How do I show a different class for every 'even' for in an ng-repeat?

I was populating an html table and needed to apply the css class 'even' to every second line.

The solution was pretty simple using some angular goodness.

My html for the tr was as follows:

<tr ng-repeat="data in MyDataCollection" ng-class="IsEven($index) ? 'even' : '' ">
<td>{{data.Col1}}</td>
<td>{{data.Col2}</td>
</tr>

The variable $index gives you the current index (row) for the collection. You can pass it to a (simple) function to return whether the row is even or not.

My function looked as follows:

$scope.IsEven = function(index){ return (index % 2 != 0); };

Sunday, 10 January 2016

AngularJS: How do I disable an anchor tag?

Normally, the easiest way to disable a control is using ng-disable, but this little beauty does not work with anchor tags.

The easiest way is to created a directive to handle the action (see here for the original code):

app.directive('aDisabled', function() {
    return {
        compile: function(tElement, tAttrs, transclude) {
            //Disable ngClick
            tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")";

            //return a link function
            return function (scope, iElement, iAttrs) {

                //Toggle "disabled" to class when aDisabled becomes true
                scope.$watch(iAttrs["aDisabled"], function(newValue) {
                    if (newValue !== undefined) {
                        iElement.toggleClass("disabled", newValue);
                    }
                });

                //Disable href on click
                iElement.on("click", function(e) {
                    if (scope.$eval(iAttrs["aDisabled"])) {
                        e.preventDefault();
                    }
                });
            };
        }
    };
});


The HTML will look something like this:
<a href="" id="btnSubmit" a-disabled="MyDisablingFunction()" />