寻找正确的方法,如何在AngularJS里使用jQuery
一、为什么还是要使用jquery
在使用Angular一段时间后,发现还是很难逃脱jquery 插件的魔掌。尽管对于angular,内置了jQLite.
但是为了更好的实现功能,不可避免的要使用一些jquery的插件。
二、如何在Angular里使用jquery
1. 如果使用jquery的插件,我们不应该把对应的code放到controller里面。我们应该创建directive,然后通常把jquery的code放在 link里面
2. 当我们引入jquery 插件库的时候,我们要保证是在最后倒入的,在angularjs,controllers,services,filters结束后引入
三、实践Plunker
如何在angular里使用jcrop
HTML
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="//deepliquid.com/projects/Jcrop/js/jquery.min.js"></script>
<script src="//deepliquid.com/projects/Jcrop/js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Hello </h1>
<button ng-click='img = "http://deepliquid.com/Jcrop/demos/demo_files/pool.jpg"'>Orig</button>
<button ng-click='img = "http://api.ning.com/files/ZC4177QOYrNFCalnvSMuQhhDHuDSN983R6Cu41iPxpbyxGhX*8BhXoXmBEcGH-zUvSNHnUxlcEJA0BZdf9ch8Q10kP8-BszV/daisy0.jpg"'>Kitten</button>
<img-cropped src='' selected='selected(cords)'>
</body>
</html>
JS
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected = function(x) {
console.log("selected",x);
};
});
app.directive('imgCropped', function() {
return {
restrict: 'E',
replace: true,
scope: { src:'@', selected:'&' },
link: function(scope,element, attr) {
var myImg;
var clear = function() {
if (myImg) {
myImg.next().remove();
myImg.remove();
myImg = undefined;
}
};
scope.$watch('src', function(nv) {
clear();
if (nv) {
element.after('<img />');
myImg = element.next();
myImg.attr('src',nv);
$(myImg).Jcrop({
trackDocument: true,
onSelect: function(x) {
scope.$apply(function() {
scope.selected({cords: x});
});
}
});
}
});
scope.$on('$destroy', clear);
}
};
});
标签:jQuery,function,插件,共存,selected,jquery,AngularJS,scope,myImg From: https://blog.51cto.com/u_8895844/6157032