2014-02-05 4 views
3

나는 각도가 비교적 새롭고 디버깅 후 몇 시간 동안 jquery를 추가 할 때 약간의 비호 환성을 발견했습니다. 이 지침은 그것으로 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'); 
    }; 

});

+0

어쩌면 내가 질문을하지 않습니다

은 더 나은 솔루션의 일종이다. 하지만 왜 trustAsHtml을 사용하십시오. 당신의 덩어리가 그것없이 잘 작동합니다. Jquery 선물 여부. http://plnkr.co/edit/vPBFWfKV7toPquQFtozH?p=preview – mainguy

답변

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> 
관련 문제