jquery打破了角度指令

时间:2014-02-05 09:01:29

标签: jquery angularjs

我对角度相对较新,经过数小时的调试后发现添加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');
    };

});

1 个答案:

答案 0 :(得分: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>