我尝试将菜单信息存储在数组中(示例中为menu_entries
)并使用指令(myMenu
)进行渲染,但存储在数组中的函数似乎不适用于ng-点击。
以下是示例:http://jsfiddle.net/5CaQx/
menu1和menu2不起作用,但menu3有效。
JS代码:
var my_app;
my_app = angular.module('myApp', []);
my_app.controller('myPageCtrl', [
'$scope', function($scope) {
$scope.menu_entries = [
{
name: 'menu1',
onclick: $scope.onMenu1Click
}, {
name: 'menu2',
onclick: $scope.onMenu2Click
}
];
$scope.say_something = "";
$scope.onMenu1Click = function() {
return $scope.say_something = "lalala";
};
$scope.onMenu2Click = function() {
return $scope.say_something = "wawawa";
};
return $scope.onMenu3Click = function() {
return $scope.say_something = "rarara";
};
}
]);
my_app.directive("myMenu", [
"$compile", function($compile) {
return {
restrict: 'E',
replace: true,
scope: {
menue: '='
},
link: function(scope, elem, attrs) {
elem.html('<div ng-repeat="me in menue"><li><div class="menu-btn" ng-click="me.onclick()"><div class="menu-text">{{me.name}}</div></div></li></div>');
return $compile(elem.contents())(scope);
}
};
}
]);
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="../css/app.css" rel="stylesheet" />
<script src="../js/angular.min.js"></script>
<script src="../js/app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myPageCtrl">
<p>
{{say_something}}
</p>
<ul>
<my_menu menue="menu_entries"></my_menu>
<li>
<div class="menu-btn" ng-click="onMenu3Click()">
<div class="menu-text">
menu3
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:0)
试试这个:
$scope.onMenu1Click = function() {
return $scope.say_something = "lalala";
};
$scope.onMenu2Click = function() {
return $scope.say_something = "wawawa";
};
//Move this code after the creating $scope.onMenu1Click and $scope.onMenu2Click
$scope.menu_entries = [
{
name: 'menu1',
onclick: $scope.onMenu1Click //onMenu1Click instead of menu1Click
}, {
name: 'menu2',
onclick: $scope.onMenu2Click //onMenu2Click instead of menu2Click
}
];