我知道在模板函数中创建的dom可以附加到controller中的事件。作为:
angular.module('app', [])
.directive('appClick', function(){
return {
restrict: 'A',
scope: true,
template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
controller: function($scope, $element){
$scope.clicked = 0;
$scope.click = function(){
$scope.clicked++
}
}
}
});
由于模板中没有范围,所以我必须使用链接功能。 同样如何在链接功能中实现。像:
angular.module('app', [])
.directive('appClick', function(){
return {
restrict: 'A',
scope: true,
link:function(scope, element, attrs){
element.html('<button ng-click="click()">Click me</button> Clicked {{clicked}} times')
},
controller: function($scope, $element){
$scope.clicked = 0;
$scope.click = function(){
$scope.clicked++
}
}
}
});
如何在此处附加活动。
答案 0 :(得分:2)
当您想要将Angularjs
附加到现有DOM
时,请DOM
。首先,您必须使用$compile
上要scope
的{{1}}服务对其进行编译。这是因为模板包含Angular js
模板语法。以下是工作片段。
var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope', function($scope){
$scope.message = 'Welcome message';
}])
myApp.directive('myTemplate', ['$compile',function($compile) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attr) {
var el = $compile('<button ng-click="click()">Click me</button> Clicked {{clicked}} times')(scope);
element.append(el);
scope.clicked = 0;
scope.click = function(){
scope.clicked++
}
}
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="mainController">
{{message}}
<div my-template></div>
</div>
</div>
答案 1 :(得分:0)
angular.module('app', [])
.directive('appClick', function(){
return {
restrict: 'A',
scope: true,
link:function(scope, element, attrs){
element.html('<button ng-click="click()">Click me</button> Clicked {{clicked}} times')
scope.clicked = 0;
scope.click = function(){
scope.clicked++
}
}
});
无需控制器即可实现此目的。