我正在尝试创建按钮(使用ng-repeat),单击时将创建其他按钮,单击这些按钮时将显示我要查找的信息。有人告诉我,Angular Directive可以解决这个问题。我创建了一个自定义指令,并尝试在我的新指令中包含ng-repeat指令。我已经看过这个StackOverflow discussion StackOverflow Discussion 2,但我仍然对如何最好地实现它有一些困惑。目前正在制定新指令,但没有文字附加到按钮上。在这种情况下,也只生成一个按钮而不是两个按钮。下面是我的代码(HTML和JavaScript)
HTML:
<div ng-app="anniversaries" class="row" ng-controller="annList">
<yearbuttons></yearbuttons>
</div>
JavaScript的:
var annApp = angular.module('anniversaries', []);
annApp.controller('annList', function ($scope) {
$scope.anns = [
//January
{'date':'January 2015','year': '45',
'names': ['Sample Name']},
{'date':'January 2015','year': '34',
'names': ['Sample Name2']}
];
});
annApp.directive('yearbuttons',function(){
return {
restrict: "E",
compile: function compile(element, attrs)
{
element.attr('ng-repeat', 'years in anns');
element.attr('class', 'btn btn-default');
element.append('{{year}} Years');
}
}
});
答案 0 :(得分:0)
除非需要反复使用,否则我个人根本不会使用指令。但如果确实如此,只需将模板和控制器粘贴到指令中就可以很容易地将其转换为指令。指令可以使用控制器而不是链接功能。
(function(){
angular.module('myApp', [])
.controller('BunchOfButtonsController', BunchOfButtonsController);
BunchOfButtonsController.$inject = ['$scope', '$log'];
function BunchOfButtonsController($scope, $log){
$scope.buttons = [];
$scope.nextLabel = "Some Text";
$scope.firstButtonClick = function(labelValue){
$scope.buttons.push({
label: labelValue,
click: function(){
$log.info(labelValue + " was clicked.");
}
});
$scope.nextLabel = "Another " + $scope.nextLabel;
};
}
})();
<div ng-app="myApp" ng-controller="BunchOfButtonsController">
Label: <input type="text" ng-model="nextLabel"/>
<button ng-click="firstButtonClick(nextLabel)">Click Me!</button>
<button ng-repeat="button in buttons" ng-click="button.click()">{{button.label}}</button>
</div>