首页 > 解决方案 > 我可以将 angularjs 控制器放入函数中然后通过按钮 onclick 事件加载它吗

问题描述

我不想在页面加载时加载控制器。我想在单击按钮后加载它。这是我的代码,帮帮我!!

    <!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>

标签: javascriptangularjs

解决方案


不要使用onclick加载控制器,而是使用ng-click指令调用加载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>


推荐阅读