0

i dont want to load controller when page is load.i want to load it after click the button. Here is my code, help me!!

    <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button onclick="myfunc()"></button>
Name: <input ng-model="name">
</div>
<script>
function myfunc(){
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
}
</script>
<p>Use the ng-model directive to bind the value of the input field to a property made in the controller.</p>
</body>
</html>
  • 4
    Possible duplicate of [AngularJS: lazy loading controllers and content](https://stackoverflow.com/questions/25168593/angularjs-lazy-loading-controllers-and-content) – 31piy Aug 24 '18 at 03:38
  • The suggested duplicate is not the best way to solve this problem. The user should use the `ng-click` directive to invoke a function that loads the ng-model. – georgeawg Aug 26 '18 at 11:19

1 Answers1

0

Instead of using onclick to load a controller, use the ng-click directive to invoke a function that loads the ng-model.

angular.module("myApp",[])
.controller('myCtrl', function($scope) {
    $scope.myfunc = function() {
        $scope.name = "John Doe";
    };
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
        <button ng-click="myfunc()">Load</button>
        Name: <input ng-model="name">
        <br>name={{name}}
</body>
georgeawg
  • 48,608
  • 13
  • 72
  • 95