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

时间:2017-09-30 15:55:37

标签: javascript angularjs

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

如何在此处附加活动。

2 个答案:

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

无需控制器即可实现此目的。