我正在学习AngularJs并且正在尝试运行自定义指令。我有一个按钮,单击按钮,我需要处理控制器内的事件。我没有在ng-click
指令上获得函数调用。我附加了plnkr
链接:Link to plnkr
// Code goes here
angular.module("app", []);
angular.module('app').controller('mainCtrl', function($scope){
$scope.developer={
name: "Pradeep Kumar L",
age: 32,
city: "Bengaluru",
friends:[
"Praveen",
"Kori",
"Kiran"
]
}
$scope.handleClick = function(){
developer.rank="friend";
console.log("button clicked..");
}
});
angular.module('app').directive('mySimpleDirective', function(){
return{
restrict: "E",
templateUrl: 'userInfoCard.html'
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
<h4>{{developer.name}}</h4>
</div>
<div class="panel-body">
<span ng-show='!!developer.age'><h4>User age: {{developer.age}}</h4></span>
<h4>User city: {{developer.city}}</h4>
<h4>Friends</h4>
<ul>
<li ng-repeat="friend in developer.friends">
{{friend}}
</li>
</ul>
<div ng-show="!developer.rank">
Rank: {{developer.rank}}
</div>
<div ng-show="!developer.rank">
<button class="btn btn-success" ng-click="handleClick(developer)">Click Me</button>
</div>
</div>
</div>
答案 0 :(得分:6)
该函数已被触发,但其中包含语法错误:
$scope.handleClick = function(){
$scope.developer.rank="friend";
console.log("button clicked..");
};
或
通常,当人们必须处理开发人员列表时,他们会使用以下方式,并且该函数将在ng-repeat中。
$scope.handleClick = function(developer){ //as far as you pass it as argument
developer.rank="friend";
console.log("button clicked..");
};
答案 1 :(得分:2)
如果你在你的plunker中打开控制台,你会看到一个错误:
ReferenceError: developer is not defined
at Scope.$scope.handleClick (script.js:18)
at $parseFunctionCall (angular.js:12456)
at callback (angular.js:21692)
at Scope.$eval (angular.js:14555)
at Scope.$apply (angular.js:14654)
at HTMLButtonElement.<anonymous> (angular.js:21697)
at HTMLButtonElement.n.event.dispatch (jquery-2.1.4.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.4.min.js:3)
你应该在函数或$ scope上添加或参数给script.js:18
答案 2 :(得分:1)
点击按钮后,您将developer
传递给handleClick
功能:
<button class="btn btn-success" ng-click="handleClick(developer)">Click Me</button>
但是,在您的javascript中,您的handleClick
函数没有developer
作为参数:
$scope.handleClick = function () { // developer is not passed in...
developer.rank="friend"; // ...so it will be undefined here
console.log("button clicked..");
}
要解决此问题,您的函数应:
$scope.handleClick = function (developer) { // developer can be passed in...
developer.rank="friend"; // ...so this WILL work!!
console.log("button clicked..");
}