【问题标题】:jquery breaks angular directivejquery打破了角度指令
【发布时间】:2014-02-05 09:01:28
【问题描述】:

我对 Angular 比较陌生,经过数小时的调试后,我发现在添加 jquery 时有些不兼容。该指令在没有 jquery 的情况下可以正常工作,但会中断:/

这是一个plnkr:

http://plnkr.co/edit/sRwqrWV1ha4Dp7lvsSAg?p=preview

var app = angular.module('plunker', []);

app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
})

app.controller('MainCtrl', function($scope, $sce, $compile) {

    $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');  

    $scope.testAlert = function () {
        alert('testing');
    };

});

【问题讨论】:

标签: jquery angularjs


【解决方案1】:

问题在于$sce.trustAsHtml不返回HTML字符串,而jQuery覆盖了.html方法。

您可以通过以下方式解决此问题:

var app = angular.module('plunker', []);

app.directive('dynamic', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
            scope.$watch(attrs.dynamic, function (html) {
                ele.html(html.$$unwrapTrustedValue());
                $compile(ele.contents())(scope);
            });
        }
    };
})

app.controller('MainCtrl', function ($scope, $sce, $compile) {

    $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');

    $scope.testAlert = function () {
        alert('testing');
    };

});

Plunkr

注意:这解决了问题,但我认为使用$$unwrapTrustedValue 不是一个好习惯。更好的解决方案是拥有一个绑定到attrs.dynamic 的模板。

这是一种更好的解决方案:http://plnkr.co/edit/xjS9gTJfyXvTL4LNzXub?p=preview

var app = angular.module('plunker', []);

app.directive('dynamic', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        template: '<span ng-bind-html="dynamic" ng-click="method()"></span>',
        scope: {
            dynamic: '=',
            method: '&'
        }
    };
})

app.controller('MainCtrl', function ($scope, $sce, $compile) {
    $scope.trustedHtml = $sce.trustAsHtml('<button>Submit</button>');
    $scope.testAlert = function () {
        alert('testing');
    };
});

HTML

<div dynamic="trustedHtml" method="testAlert()"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多