Reputation: 67
I like to add custom directory in element which is run-time added from script.
eg: <input type="number" my-focus = "focusField" >
in this i am adding 'my-focus' directive from html.
Can I add this directive from JavaScript because my element is dynamically added and I want to add focus on that element.
Upvotes: 0
Views: 335
Reputation: 133413
You can use $compile
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
Here is an example
$scope.html = $compile('<a ng-click="click()" href="#">Click me</a>')($scope);
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope','$compile',
function($scope, $compile) {
$scope.html = $compile('<a ng-click="click()" href="#">Click me</a>')($scope);
angular.element(document.querySelector('#x')).append($scope.html);
$scope.click = function() {
console.log('Yahoooooooooooo')
}
}
]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div id="x">
</div>
</div>
</div>
Upvotes: 2