2

I am using angular js, and want to define actions on a button that presents a loading spinner, then loads some content. I am trying to make correct separation between view and controller, but I can't think how to do it properly.

Currently, I am setting a variable in the controller, and watching it in the view - but it seems a bit long winded.

HTML

<div ng-app="myApp">
    <div ng-controller="inControl">
        <button ng-click="doIt()">Cool <i ng-show="loading">...</i></button>
    </div>
</div>

JS

var app = angular.module('myApp', []);

function inControl($scope) {
    $scope.loading = false
    $scope.doIt = function(){
        $scope.loading = true
        setTimeout(function(){
            $scope.loading = false
            $scope.$apply()
        }, 500)
    };
}

Fiddle: http://jsfiddle.net/billymoon/4es3h/

What is the proper way to handle this scenario using angular js?

1

1 Answer 1

1

This is pretty much exactly what I've done in the past.

Additionally, you might want to add some protection to stop double clicks:

$scope.doIt = function(){
    if($scope.loading == false) {
        $scope.loading = true
        setTimeout(function(){
            $scope.loading = false
            $scope.$apply()
        }, 500);
    }
};

If you're doing the same sort of button in multiple places, wrapping up the concept into a directive would neaten things up and allow you modify the underlying behaviour if you change your approach down the line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.