AmazingDayToday
AmazingDayToday

Reputation: 4282

Angular script gets executed (fired) after page load

Here's the code:

<html>
    <head>
        <script type='text/javascript'>
            var myAppModule = angular.module('myApp', []);

            myAppModule.factory('studentFactory', function (){
                // The whole factory goes here.
            });

            myAppModule.controller('studentsController', ['$scope', 'studentFactory', function ($scope, studentFactory){
                $scope.students = [];
                studentFactory.getStudents(function (data){
                    $scope.students = data;
                });
                studentFactory.removeStudent(function (data){
                    alert('test');
                    $scope.students = data;
                });
            }])
       </script>
</head>
<body ng-app='myApp'>
    ...
</body>
</html>

The alert('test') gets fired when page loads. How can I fix it? Please nevermind the issues in code, I am just working on it.

Here's the code in Plunker: https://plnkr.co/edit/u7c13AIdKPjmdkzRUPXd?p=preview

Upvotes: 1

Views: 290

Answers (1)

Brant
Brant

Reputation: 1788

This is because you're calling the functions removeStudents in the controller on instantiation. If you want it to wait for some event before firing, you need to bind it to the event. For instance, you'd wrap it in some click function like so:

$scope.whenIClickMyButton = function () {
    studentFactory.removeStudent(function (data){
        alert('test');
        $scope.students = data;
    });
}

<button ng-click="whenIClickMyButton()">Click Me</button>

And the add that as the click event. For now, it fires every time you instantiate the controller because you're calling it every time.

Upvotes: 0

Related Questions