AngularJS动态表单字段ID,指令不起作用
尝试将指令添加到具有动态id的输入时,链接方法无法正确绑定到该对象。 给出以下jsfiddle或html:
Date:
并且js:
var module = angular.module('myApp', []); module.directive('datepicker', function() { var linker = function(scope, element, attrs) { element.datepicker(); } return { restrict: 'A', link: linker } }); function MyCtrl($scope) { $scope.id = 7 }
我在控制台调试器上看到的是,当调用链接时,它会将id显示为“datepicker – {{id}}”而不是“datepicker-7”。
有没有办法强迫这种情况发生? 实现这个的更好方法是什么?
更新 :应该澄清一下。 单击时会显示日期选择器,但单击日期不起作用。 我收到错误:“此日期选择器未捕获的实例数据”
我相信你需要transclude:true
在你的指令返回对象中,它告诉angular预处理像{{ }}
绑定这样的东西的标记。
您还需要在$timeout
中包含对datepicker()
的调用以延迟尝试,直到下一个角度循环运行,从而确保在DOM中设置了被转换的ID。
这在jsfiddle中对我有用
var module = angular.module('myApp', []); module.directive('datepicker', function($timeout) { var linker = function(scope, element, attrs) { $timeout( function(){ element.datepicker(); }); } return { restrict: 'A', link: linker, transclude: true } }); function MyCtrl($scope) { $scope.id = 7 }