目录[-] (1)javascript 数组 (2)函数基础 (3)运算符 (4)流程语句 (5)正则表达式 (6)字符串函数 (7)数据类型…
June 7, 2016
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); } }; });
参考
Correct way to integrate Jquery plugins in Angular.js
An approach to use jQuery Plugins with AngularJS
Use jQuery Plugin With AngularJS the Easy (Lazy) Way
原文:http://gyf1.com/blog/2014/03/20/angularjs-jquery-%E5%85%B1%E5%AD%98%E6%B3%95%E5%88%99/