我是AngularJS的新手。所以,请为这样一个愚蠢的问题道歉。
我想隐藏/显示基于按钮点击的指令。
<body ng-app="app" ng-controller="appCtrl">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Welcome to the world of directives!</a>
</div>
<ul class="nav navbar-nav">
<li ng-repeat="fruit in fruits" ng-clicked="itemClicked(fruit.label)" style="cursor:pointer">
<a>{{fruit.label}}</a>
<my-div></my-div>
</li>
</ul>
</div>
</nav>
<script>
var app = angular.module('app',[]);
app.controller('appCtrl',function($scope){
// Fruits
$scope.fruits = [{
label:"Apple"
},{
label:"Orange",
},{
label:"Grapes"
}];
});
app.directive('myDiv',function(){
return {
restrict: 'E',
link : function(scope,elem,attrs){
scope.itemClicked = function(value){
alert('myDiv clicked : ' + value);
}
}
}
});
</script>
</body>
Whenever a link in clicked
,我想show the alert with the respective fruit name
来自指令函数。
但是在控制台中没有错误。
我错过了什么?
请说明。
答案 0 :(得分:0)
而不是在指令中定义函数,而不是在控制器中定义它,如下所示
app.controller('appCtrl',function($scope){
// Fruits
$scope.fruits = [{
label:"Apple"
},{
label:"Orange",
},{
label:"Grapes"
}];
$scope.itemClicked = function(value){
alert('myDiv clicked : ' + value);
}
});
And also change ng-click="itemClicked(fruit.label)" in your html as well.