问题
I am relatively new to JavaScript and AngularJS.
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 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.
回答1:
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);
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>
回答2:
FYI Example of set attribute, remove attribute
<!DOCTYPE html>
<!DOCTYPE html>
<html ng-app="" ng-controller="myCtrl">
<body>
<button ng-click="getAttr()">
Get Attribute value
</button>
<br/>
<button ng-click="setAttr()">
Set Attribute value
</button>
<br/>
<button ng-click="removeAttr()">
Remove Attribute value
</button>
<br/>
<div myattr="val" id="divID">
Attribute DIV
</div>
<script>
function myCtrl($scope) {
$scope.getAttr = function() {
var myEl = angular.element( document.querySelector( '#divID' ) );
alert(myEl.attr('myattr'));
}
$scope.setAttr = function() {
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.attr('myattr',"attr val");
alert("attribute set");
}
$scope.removeAttr = function() {
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.removeAttr('myattr');
alert("attribute removed");
}
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
来源:https://stackoverflow.com/questions/56782047/how-to-add-angular-attributes-to-dynamically-generated-element-with-a-function-a