简体   繁体   English

在元素中以编程方式(而不是HTML)添加自定义指令

[英]add custom directive in element programmatically instead of HTML

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. 例如: <input type="number" my-focus = "focusField" >在此,我从html添加了“ my-focus”指令。

Can I add this directive from JavaScript because my element is dynamically added and I want to add focus on that element. 我可以从JavaScript添加此指令,因为我的元素是动态添加的,并且我想重点关注该元素。

You can use $compile 您可以使用$ 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. 将HTML字符串或DOM编译到模板中,并生成模板函数,然后可以使用该函数将范围和模板链接在一起。

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> 

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

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