使用angularjs添加包含事件的新标记

时间:2015-09-30 04:30:27

标签: javascript angularjs

我需要在其中添加一个带有事件的新html标记,例如:

.main .img-container {
    background-color: #ddd;
    /*max-height: 100%;*/
    height: 100%;
    width: 80%;
}

如何在angularjs中添加事件?

1 个答案:

答案 0 :(得分:0)

试试这个

<section ng-app="myApp" ng-controller="MainCtrl">
    <addbuttonsbutton></addbuttonsbutton>
    <div id="space-for-buttons"></section>
</section>

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MainCtrl($scope) {
	$scope.count = 0;
}

//Directive that returns an element which adds buttons on click which show an alert on click
myApp.directive("addbuttonsbutton", function(){
	return {
		restrict: "E",
		template: "<button addbuttons>Click to add buttons</button>"
	}
});

//Directive for adding buttons on click that show an alert on click
myApp.directive("addbuttons", function($compile){
	return function(scope, element, attrs){
		element.bind("click", function(){
			scope.count++;
			angular.element(document.getElementById('space-for-buttons')).append($compile("<div><button class='btn btn-default' data-alert="+scope.count+">Show alert #"+scope.count+"</button></div>")(scope));
		});
	};
});

//Directive for showing an alert on click
myApp.directive("alert", function(){
	return function(scope, element, attrs){
		element.bind("click", function(){
			console.log(attrs);
			alert("This is alert #"+attrs.alert);
		});
	};
});
&#13;
&#13;
&#13;