简体   繁体   中英

can i put angularjs controller into function then load it by button onclick event

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>

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> 

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