[英]AngularJS - function within controller isn't being called as I would expect in simple example
For the following HTML and JS controller, why is the 'clear' button not triggering the function? 对于以下HTML和JS控制器,为什么“清除”按钮未触发功能?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app" ng-controller="resetController as reset">
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<button ng-click="clearName">Clear</button>
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
And the app.js file 还有app.js文件
angular.module('app', [])
.controller('resetController', function($scope) {
$scope.yourName = 'Start';
$scope.clearName = function(){
console.log('clearing name...');
$scope.yourName = '';
};
});
I believe you are missing '()', I believe you have to write the function as if it is being called, eg 我相信您缺少'()',我相信您必须像调用函数一样编写函数,例如
<button ng-click="clearName()">Clear</button>
Additionally, I can see that you are using the controllerAS syntax, so you would normally end up with: 此外,我可以看到您正在使用controllerAS语法,因此通常会得到以下结果:
<button ng-click="reset.clearName()">Clear</button>
However, I think you need to bind the function to the controller and not the scope object in that case. 但是,我认为您需要将函数绑定到控制器,而不是那种范围对象。 eg
例如
angular.module('app', [])
.controller('resetController', function() {
var self = this;
self.yourName = 'Start';
self.clearName = function(){
console.log('clearing name...');
self.yourName = '';
};
});
It is a long read, but have a look at https://github.com/johnpapa/angular-styleguide . 这是一本很长的书,但是请参阅https://github.com/johnpapa/angular-styleguide 。
Good luck. 祝好运。
clearName()是一个函数,因此需要括号。
<button ng-click="clearName()">Clear</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.