【问题标题】:Should I place this jquery inside an angular controller?我应该将此 jquery 放在角度控制器中吗?
【发布时间】:2015-01-26 22:37:44
【问题描述】:

在一个 html 表中,我有一个使用 ng-repeat 构造的行列表。在这些行中,我有一个使用 jquery 更改样式的单选按钮。使用此 jquery 应用样式...

<script>
$(document).ready(function () {
$('.i-checks').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green'
});
});
</script>

当我将此代码放在页面中时,单选按钮样式不起作用。但是,如果我将代码放在表格行中 - 它确实有效......

<div ng-controller="supplierController" class="row">
<div class="col-lg-6 m-t-m">
<div class="ibox float-e-margins">
    <div class="ibox-title">
        <h5>Price results </h5>
    </div>
    <div class="ibox-content">

        <table class="table table-striped">
            <thead>
            <tr>
                <th>Vendor</th>
                <th>Details</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="supplier in suppliers.prices">
                <td>{{ supplier.supplier_name }}</td>
                <td>£{{ supplier.price }}</td>
                <td>
                    <div class="radio i-checks"><label> <input
type="radio"  name="a"> <i>this</i></label>
 <script>
            $(document).ready(function () {
                $('.i-checks').iCheck({
                    checkboxClass: 'icheckbox_square-green',
                    radioClass: 'iradio_square-green'
                });
            });
        </script>

</div>

                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

这行得通——但显然这是一个糟糕的主意,因为 jquery 是为每一行呈现的。所以我的问题是,放置此代码的最佳位置在哪里,以便它也可以工作?我应该把它放到控制器中吗?

抱歉,如果我不清楚,我是 Angular 的新手。

非常感谢

【问题讨论】:

  • 如果它与 dom 交互(在这种情况下,这是真的)它应该在一个指令中。到目前为止,我看到的唯一例外是在创建服务来处理对话框或警报时。

标签: jquery angularjs controller radio-button


【解决方案1】:

只针对插件部分的指令真的很容易组合在一起

angular.module('YourApp').directive('iChecks', function () {    
    return {
        restrict: 'C', // for class in markup
        link: function (scope, element, attrs) {
            // element is jQuery object (see note below)
            element.iCheck({
                checkboxClass: 'icheckbox_square-green',
                radioClass: 'iradio_square-green'
            });
        }
    }
});

将要求您在页面中包含 jQuery.js before angular.js。当您这样做时,angular.element 使用完整的 jQuery 库。

接下来的步骤是添加行为。请注意,任何修改范围的事件都需要使用 scope.$apply() 来告诉 Angular 运行摘要循环

【讨论】:

    【解决方案2】:

    正如你所说的那样,你正在做的是一个糟糕的主意。正如 Kevin 在评论中所说,您应该创建一个指令。

    我创建了一个小要点来启用任意 JQuery 插件。

    https://gist.github.com/ameyms/4f3a5d6a8d329609d44e

    PS:我没测试过,不知道好不好用!

    【讨论】:

    • 只是一个建议,在要点中添加一个使用视图。
    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2013-09-07
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多