【问题标题】:AngularJS applying jquery after ng-include html templateAngularJS在ng-include html模板之后应用jquery
【发布时间】:2015-03-21 14:47:03
【问题描述】:

我正在使用一个名为 jquery masked input 的插件。 http://digitalbush.com/projects/masked-input-plugin/ 用于屏蔽cell phonessn 如下:

<script type="text/javascript">
    $('.mask-ssn').mask('999-99-9999');
    $('.mask-phone').mask("(999) 999-9999");
</script>

我有一个 Angular 应用程序,它通过 ng-include 加载表单

<div class="myForm" data-ng-include="'/templates/_form.html'"></div>

而_form.html的简化内容如下:

<div class="form-group">
    <input 
        class="form-control mask-phone" 
        type="text" 
        placeholder="Cell Phone" 
        name="cell_phone" 
        required 
        data-ng-pattern="user.phone_number_regex"
        data-ng-model="user.formData.cell_phone"/>
    <div class="help-block">...</div>
</div>

如果我只是将 _form.html 内容粘贴到父页面中,一切都会正常工作,并且 jquery 屏蔽输入将应用于 html。

不幸的是,由于 _form.html 正在异步加载,jquery 屏蔽输入插件不起作用。

寻找一些关于*最佳实践/自以为是的*方法将掩码应用于 html 的建议。不知道是否沿着将 $scope 注入我的角度控制器然后使用 $scope.apply 的路线。或者通过创建指令/或替代解决方案?

【问题讨论】:

  • 您可以使用 grunt-angular-templates 添加到 $templateCache,而不是从 http 请求加载 (_form.html)。通常,我将 jQuery 调用包装在 setTimeout 中,因为大多数都可以在角度摘要之外执行,但这只是我的意见。

标签: jquery angularjs asynchronous angularjs-directive angularjs-scope


【解决方案1】:

这是因为 ng-include 创建了一个新的子作用域。您可以尝试像这样添加 $parent:

<div class="form-group">
    <input 
        class="form-control mask-phone" 
        type="text" 
        placeholder="Cell Phone" 
        name="cell_phone" 
        required 
        data-ng-pattern="$parent.user.phone_number_regex" //add $parent.
        data-ng-model="$parent.user.formData.cell_phone"/> // the same here.
    <div class="help-block">...</div>
</div>

【讨论】:

  • 感谢您的回答,但不确定这是如何解决问题的。问题在于 jQuery 屏蔽输入插件。不是我的正则表达式/模型。
【解决方案2】:

通过将 jquery 屏蔽输入包装在指令中解决的问题

app.directive('mask', function(){
    return {
        restrict: 'A',
        link: function (scope, elem, attr, ctrl) {

            if (attr.mask)
                elem.mask(attr.mask, { placeholder: attr.maskPlaceholder });
        }
    };
});

然后是 SSN 和单元格的 html 元素

<input class="form-control" data-mask="(999) 999-9999" type="text".../>
<input class="form-control" data-mask="999-99-9999" type="text".../>

还有更好的解决方案吗?

【讨论】:

  • 我认为这是最好的解决方案,在 angularjs 应用程序中,您应该将任何第三方(jquery 插件)包装到指令中。这是有角度的方式:)
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 2015-10-01
  • 2013-11-21
  • 1970-01-01
  • 2018-07-18
  • 2014-11-08
  • 2021-09-17
  • 2017-02-07
相关资源
最近更新 更多