当我通过指令传递ID时遇到问题。我无法在Link函数中使用jQuery获取元素,并且元素使用正确的动态ID作为参数:
指令:
(function(angular) {
var app = angular.module('pi.core');
app.directive('piSearch', function() {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
idelement: '@'
},
link: function(scope, element, attrs, controller, transcludeFn) {
var idelement = scope.idelement;
console.log('idElement: ' + idelement);
console.log($('#' + idelement + ' .typeahead'));
},
template: '<div id="{{idelement}}"></div>'
};
});
})(angular);
var myApp = angular.module('piCore', []);
myApp.directive("piSearch", function() {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
idelement: '@'
},
link: function(scope, element, attrs, controller, transcludeFn) {
var idelement = scope.idelement;
scope.elementSelected = $('#' + idelement + ' .typeahead');
console.log('idElement: ' + idelement);
console.log($('#' + idelement + ' .typeahead'));
},
template: '<div id="{{idelement}}"></div>'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body ng-app="piCore">
<pi-search></pi-search>
{{$scope.elementSelected}}
</body>
任何提示?在此先感谢您的帮助!
答案 0 :(得分:1)
尝试使用angular.element("#"+ idelement);
并确保多次生成此template: '<div id="{{idelement}}"></div>'
答案 1 :(得分:1)
我会重构您的链接功能,请记住angular有自己的生命周期,并且您需要确保模板在您的模型有值时编译,将您的逻辑包装在手表中
app.directive('piSearch', function() {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
idelement: '@'
},
link: function(scope, element, attrs, controller, transcludeFn) {
var idelement = scope.idelement;
scope.$watch('idelement',function(){
scope.elementSelected = $('#' + idelement + ' .typeahead');
console.log('idElement: ' + idelement);
console.log($('#' + idelement + ' .typeahead'));
});
},
template: '<div id="{{idelement}}"></div>'
};
});
答案 2 :(得分:0)
您必须了解有关全局动态ID和元素的一件事:
1)首先,你必须在javascript中生成动态HTML
2)打印,追加或只是在DOM中插入som
3)现在要访问该新元素,您必须使用document
来读取这样的新元素:
document.getElementById('new-generic-id');
或
$(document).on('click touchstart select', '#new-generic-id', function(){});
我希望你明白。