jQuery的replaceWith后评估自定义指令 [英] Evaluating Custom Directive after jQuery replaceWith
问题描述
我有以下的code:
<div ng-app="myApp" ng-controller="AngularCtrl">
<a href="#" id="click_btn">Click here</a>
</div>
<script>
jQuery("#click_btn").click(function(){
jQuery(this).replaceWith('<p>Hello {{student.name}}</p><div my-repeater></div>');
});
</script>
下面是我的角度code:
Here is my angular code:
var myApp = angular.module('myApp',[]);
myApp.directive('myRepeater', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var myTemplate = "<div>{{rating}}</div>";
for(var i=0;i<scope.items.length;i++)
{
var myItem = scope.items[i];
var text = myTemplate.replace("{{rating}}",myItem.rating);
element.append(text);
}
}
};
});
function AngularCtrl($scope) {
$scope.student = {id: 1, name: 'John'};
$scope.items = [{id: 1, ratings: 10}, {id: 2, ratings: 20}];
}
在这里,每当我点击按钮,该元素才刚刚更换,不进行评估。我试着用angular.bootstrap(文件);后文件已准备就绪。
Here, whenever i click on the button, the element is just getting replaced and not evaluated. I tried with "angular.bootstrap(document);" after document is ready.
但是,这只是评估角度对象。不过还是自定义指令我直放站是没有得到评估。如何我可以完成这件事的任何帮助吗?
But that just evaluates the angular objects. But still the custom directive "my-repeater" is not getting evaluated. Any help on how can i get this done?
推荐答案
首先,我想这是考验code,因为有角的 NG-重复,该适合您的需求。
First of all, I suppose this is test code, since angular has ng-repeat, which fits your needs.
有您的code几个问题:
There are several issues with your code:
1)你不应该使用 myTemplate.replace ,但使用的 $编译服务。注入$编译服务到您的指令(如添加功能参数),并使用它:
1) You shouldn't use myTemplate.replace, but use the $compile service. Inject the $compile service into your directive (add as function param) and use it:
var text = $compile(myTemplate)(scope);
2)控制器上的项目将不会在你的指令进行访问。添加它作为一个价值,你我的中继器属性:
2) Items on the controller will not by accessible in your directive. Add it as a value to your my-repeater attribute:
<div my-repeater='{{items}}'>
在您的指令,您需要评估我的中继器:
In your directive you need to evaluate my-repeater:
var items = scope.$eval(attrs.myRepeater);
3)的jQuery(本).replaceWith 不会开球角度,因为它的范围。您需要使用范围做手工。$适用。但最好是在该指令链接功能添加单击事件:
3) jQuery(this).replaceWith will not kickoff angular, since it it out of its scope. You need to do it manually by using scope.$apply. But is better to add the click event in the directive link function:
link: function(scope, element, attrs) {
element.on('click', function() {
...
scope.$apply();
});
编辑:这是一个工作例如
这篇关于jQuery的replaceWith后评估自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!