[英]How to integrate a jQuery function in angularjs?
I want to add the following jQuery
function to an existing angularjs
application: 我想将以下
jQuery
函数添加到现有的angularjs
应用程序:
$.fn.stars = function() {
return this.each(function(i,e){$(e).html($('<span/>').width($(e).text()*16));});
};
$('.stars').stars();
http://jsbin.com/IBIDalEn/2/edit?html,css,js,output http://jsbin.com/IBIDalEn/2/edit?html,css,js,output
The html for this should be: 这个html应该是:
Rating: <span class="stars">4.3</span>
But: where do I have to put the jquery function in order to work with angularjs? 但是:我必须在哪里放置jquery函数才能使用angularjs? And where do I have to call this
$('.stars').stars();
我在哪里可以称之为
$('.stars').stars();
? ?
I know this isn't answering your question directly @Michael does a good job of that. 我知道这不是直接回答你的问题@Michael做得很好。 However i think its worth noting that for something as simple as this there is no need for jquery.
但是我认为值得注意的是,对于像这样简单的东西,不需要jquery。 You could roll out your own simple directive and do it right with angular.
您可以推出自己的简单指令,并使用angular进行操作。 Plus you leverage data binding to make it update itself.
此外,您利用数据绑定使其自行更新。
Plus Michael
doesn't answer the issue of where do you extend JQuery to use your custom stars()
method? 加上
Michael
没有回答你在哪里扩展JQuery以使用自定义stars()
方法的问题? It shouldn't be in the directive otherwise it will be called every time a directive is added to the page. 它不应该在指令中,否则每次将指令添加到页面时都会调用它。 (image if it was in a
ng-repeat
) (如果是
ng-repeat
)
.directive('stars', function () {
return {
restrict: 'EA',
template: '<span class="stars"><span ng-style="style"></span></span>{{stars}}',
scope: {
stars: '='
},
link: function ($scope, elem, attrs){
$scope.$watch('stars', set);
function set(){
$scope.style = {
width: (parseFloat($scope.stars) * 16) + '%'
};
}
}
}
});
Its quite simple you define your template, the two spans. 您可以非常简单地定义模板,即两个跨度。 Then you watch the
$scope.stars
property so you can update your rating should the value change. 然后,您观察
$scope.stars
属性,以便在值更改时更新您的评级。
see fiddle: http://jsfiddle.net/g7vqb5x9/1/ 看小提琴: http : //jsfiddle.net/g7vqb5x9/1/
You should never manipulate the DOM inside a controller. 你永远不应该操纵控制器内的DOM。 A directive link is the correct spot for DOM manipulation.
指令链接是DOM操作的正确位置。
Angular.element is already a jQuery object: Angular.element已经是一个jQuery对象:
angular.module('app', [])
.directive('stars', function() {
return {
restrict: 'C',
link: function($scope, element) {
element.stars();
}
};
});
BTW: a span
is an inline element and has NO height and width. BTW:
span
是一个内联元素,没有高度和宽度。 you need to use a block element or override the display attribute. 您需要使用块元素或覆盖display属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.