繁体   English   中英

如何将事件附加到链接功能中创建的dom

[英]How to attach event to dom created in link function

我知道可以在模板函数中创建的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++
             }
           }
         }
       });

如何在此处附加活动。

要在Angularjs某些DOM附加到现有DOM 首先,您必须在要使用模板的scope使用$compile服务对其进行$compile 这是因为模板包含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> 

 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++
             }
         }
       });

无需控制器即可实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM