如何使用函数作为参数将Angular属性添加到动态生成的元素? [英] How to add Angular attributes to dynamically generated element with a function as the parameter?

查看:76
本文介绍了如何使用函数作为参数将Angular属性添加到动态生成的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript和AngularJS比较陌生.

I am relatively new to JavaScript and AngularJS.

我一直在尝试使用以下代码向功能为参数的链接元素添加"ng-click"属性:

I have been attempting to add an 'ng-click' attribute to a link element with a function as the parameter using the code below:

var aTag1 = document.createElement('a');               
aTag1.setAttribute('ng-click', "setID(" + response.data[i].resultID + ")");

JavaScript似乎承认该属性已添加到元素中,但是单击链接时该函数未运行.我敢肯定有一个简单的答案,但是由于某种原因我一直找不到.

JavaScript seems to acknowledge that the attribute has been added to the element but the function isn't run when the link is clicked. I'm sure there is a simple answer but I haven't been able to find one for some reason.

推荐答案

在创建元素并使用方法设置属性时,请使用 $ compile 编译新内容,然后追加./p>

When you create the element and set the attributes using your method, please compile the new content using $compile and then append.

var aTag1 = document.createElement('a');
aTag1.innerHTML = 'testing'
aTag1.setAttribute('ng-click', "setID(" + "'test'" + ")");
var test = $compile(aTag1)(scope);
element.append(test);

请检查以下工作示例,该逻辑也应在angular指令内完成,因为我们正在修改元素.

Please check the below working example, also this logic should be done inside an angular directive, since we are modifying the element.

angular.module('components', []).directive('helloWorld', function($compile) {
  return {
    restrict: 'E',
    scope: {
      name: '='
    },
    template: '<span>Hello {{name}}</span>',
    link: (scope, element, attrs) => {
      var aTag1 = document.createElement('a');
      aTag1.innerHTML = 'testing'
      aTag1.setAttribute('ng-click', "setID(" + "'test'" + ")");
      var test = $compile(aTag1)(scope);
      element.append(test);
      scope.setID = function(value) {
        console.log(value);
      }
    }
  }
})

angular.module('myApp', ['components']).controller('myctrl', ['$scope', function($scope) {
  $scope.name = 'test';
}]);

.ng-scope {
  border: 1px red solid;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller='myctrl'>
  <hello-world name="name"></hello-world>
  <div>

这篇关于如何使用函数作为参数将Angular属性添加到动态生成的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆