Dubby
Dubby

Reputation: 1144

How to use onload attribute with ng-controller directive to execute a function defined within the controller?

I have to call the submit() function the moment the page loads. However this sort of arrangement gives a submit() method not found error. I am unable to understand the placement of ng-controller and onload.

Also if there is any alternative way of doing this with angular, please point that out as well.

PS: This is a code snippet. All variables have been defined.

<body ng-controller="DashboardDisplay" onload="submit()">
    <div class="container-fluid" >

        {{scope.arr}}
    </div>
</body>
<script>

var myApp = angular.module('myApp',[]);
myApp.controller('DashboardDisplay', ['$scope','$http',function($scope,$http) {

    $scope.submit = function(){
        var jsonOb = {"A":"B"};
        $http.post(URL,jsonOb).
        success(function(response) {
            console.log('got it' + response);
            $scope.arr=response;
        }).
        error(function(data, status, headers, config) {
        console.log('nufin' + status);
        });
    }
    }]);

Upvotes: 0

Views: 592

Answers (1)

User2
User2

Reputation: 1293

Use ng-init instead of onload i.e

<body ng-controller="DashboardDisplay" ng-init="submit()">

And removed scope which before arr in html i.e {{scope.arr}} to {{arr}}

I have created working DEMO https://jsfiddle.net/Shital_D/x2k8n23n/1/

Upvotes: 1

Related Questions