我想将以下 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
这个的 html 应该是:
Rating: <span class="stars">4.3</span>
但是:为了与 angularjs 一起工作,我必须将 jquery 函数放在哪里?我必须在哪里调用此 $('.stars').stars();
?
最佳答案
我知道这不是直接回答您的问题@Michael 做得很好。但是我认为值得注意的是,对于像这样简单的事情,不需要 jquery。你可以推出你自己的简单指令,并用 angular 来做。此外,您还可以利用数据绑定(bind)使其自行更新。
Plus Michael
没有回答您在哪里扩展 JQuery 以使用自定义 stars()
方法的问题?它不应该在指令中,否则每次将指令添加到页面时都会调用它。 (图像如果它在 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) + '%'
};
}
}
}
});
定义模板非常简单,两个跨度。然后观察 $scope.stars
属性,以便在值发生变化时更新您的评分。
参见 fiddle :http://jsfiddle.net/g7vqb5x9/1/
关于javascript - 如何在 angularjs 中集成 jQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902323/