AngularJS动态表单域ID与指令无法正常工作 [英] AngularJS dynamic form field ID with a directive not working

查看:246
本文介绍了AngularJS动态表单域ID与指令无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图一个指令添加到一个输入与一个动态的id,连结方法不正确地绑定到对象。鉴于以下的jsfiddle 或HTML:

When trying to add a directive to a input with a dynamic id, the link method does not properly bind to the object. Given the following jsfiddle or html:

<div ng-app="myApp" ng-controller="MyCtrl">
  <p>Date: <input type="text" id="datepicker-{{id}}" datepicker></p>    
</div>

和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字面上。日期选择器 - {{ID}},而不是日期选择器-7

What I see on the console debugger is that when link is called it is showing the id literally as "datepicker-{{id}}" and not "datepicker-7".

有没有办法迫使这种情况发生?实现这个更好的办法?

Is there a way to force this to happen? A better way to implement this?

更新:本来应该澄清。当点击,但点击日期不起作用的日期选择器显示出来。我得到的错误:此日期选择未捕获缺少实例数据

Update: Should have clarified. The datepicker shows up when clicked, but clicking on a date does not function. I get the error: "Uncaught Missing instance data for this datepicker"

推荐答案

我相信你需要 transclude:真正的在你的指令返回的对象,它告诉角度为preprocess的东西标记像 {{}} 绑定。

I believe you need transclude:true in your directive return object, which tells angular to preprocess the markup for things like {{ }} bindings.

您还需要包装)在 $超时调用日期选择器( 推迟尝试,直到下一个角周期运行,确保translcuded ID被在DOM设置

You also need to wrap the call to datepicker() in a $timeout to delay the attempt until the next angular cycle runs, ensuring that the translcuded ID is set in the DOM.

这在的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
}

这篇关于AngularJS动态表单域ID与指令无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆