2

I am new to AngularJS and I created a modal as described on http://angular-ui.github.io/bootstrap/ which opens on the click of a button. However, I also want it to open directly when the page loads, as some critical settings need to be entered in the modal. To this end, I directly call the open function when the controller is initialized and I was wondering whether this is a good or a bad practice, as I can't seem to find a better solution.

This is my Javascript code:

angular.module('myApp', ['ui.bootstrap'])

.controller('NavBarCtrl', ['$scope', '$modal', function($scope, $modal) {
    $scope.openSettings = function() {
        var settingsInstance = $modal.open({
            templateUrl: 'settingsTemplate',
            controller: 'SettingsInstanceCtrl',
            scope: $scope
        });
    }

    $scope.reset = function() {
        alert('Not implemented yet');
    };

    $scope.openSettings();
}])

.controller('SettingsInstanceCtrl', ['$scope', '$modalInstance', function($scope, $modalInstance) {
    $scope.closeSettings = function() {
        $modalInstance.dismiss('closed');
    }

    $scope.saveSettings = function() {
        //save
        $modalInstance.dismiss('saved');
    }
}]);

As you can see in the code, the closeSettings function of the controller's scope is immediately called when the $scope is set. Any feedback would be welcome.

Thanks a lot!

1
  • It's not uncommon that you'll find a call to a scope function at the bottom of a controller, so that it runs upon instantiation. The question is whether there are problems with calling this particular function. None are obvious to me. Commented May 28, 2014 at 15:43

1 Answer 1

1

This really depends, wether you want to reuse this controller in another view / app without this behaviour:

YES: You could then use a nested element such as

<span ng-init="openSettings()">

that would call the controller action, or use ng-init it directly on the same element.

NO: Well, this is perfectly fine i do it all the time if this shall be the standard way your controller works.

Regarding best practices i would recommend splitting your controllers into separate files SettingsInstanceCtrl.js, NavBarCtrl.js if your app grows larger.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.