I am learning AngularJs and was trying to run a custom directive. I have a button and on click of the button, I need to handle to event inside my controller. I am not getting the function call on ng-click directive. I am attaching the plnkr link: 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>
The function is triggered but you have a syntax error inside it :
$scope.handleClick = function(){
$scope.developer.rank="friend";
console.log("button clicked..");
};
or
Usually, people use the following way when they have to deal with a list of developers, and the function would have been inside a ng-repeat.
$scope.handleClick = function(developer){ //as far as you pass it as argument
developer.rank="friend";
console.log("button clicked..");
};
http://plnkr.co/edit/vsRr9CfXxK0HQ7XS5GFe?p=preview
if you switch on console in your plunker you will see an error:
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)
you should add or argument on function or $scope to line script.js:18
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With