javascript - 我可以将 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>
解决方案
不要使用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>
推荐阅读
- levenshtein-distance - ImportError:无法从“Levenshtein”(未知位置)导入名称“ratio”
- javascript - 如何自动从站点下载文件?
- c - 我如何避免这种原子操作的竞争条件?
- asp.net - 如何通过 HttpWebRequest 传递值
- scala - 如何对变量字符串进行子串化
- javascript - React Context API 和组件方法
- php - Laravel无法删除记录,但方法指定为delete
- c - 我对执行流程感到震惊,任何人都可以帮助我
- django - 当我在 django 视图中更新时,我可以自己命名该字段吗?
- r - 如何grep与模式匹配的列并计算这些列的行均值并将平均值作为新列添加到r中的数据框?