简体   繁体   中英

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);
        });
    }
    }]);

Use ng-init instead of onload ie

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM