jquery is a very powerful js framework, and angularjs is a very powerful front-end mvc framework. Although using any one of these frameworks is sufficient for the project, sometimes the two frameworks need to be mixed, although it is not recommended. But sometimes it’s very convenient when used together. Don’t think too much about it. As long as it can achieve the function, why not do it?
A product I recently made uses angularjs for the front end, but jquery.datatables.js is used for the table framework. Of course, there are inevitably problems with the interaction between jquery and angularjs. Due to the company's confidentiality, I won't use the real project demonstration and write a small demo. Of course, the real project is much more complicated.
<!DOCTYPE html> <html ng-app="ngDemo"> <head> <title></title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script src="//www.w3cschool.cc/try/angularjs/1.2.5/angular.min.js"></script> <script type="text/javascript"> $(function() { $('#btn').on('click',function(e) { $('#dv2').text(Number($('#dv2').text())+1);//jquery+angular实现 $('#dv3').text(Number($('#dv3').text())+1);//纯jquery实现 }); }); var app=angular.module('ngDemo',[]); app.controller('ngCtrl',['$scope',function ($scope) { $scope.test1=0; $scope.test2=0; }]); </script> </head> <body ng-controller="ngCtrl"> test1:<div id="dv1">{{test1}}</div><!--纯angular实现--> test2:<div id="dv2" ng-bind="test2" ng-model="test2"></div> test3:<div id="dv3">0</div> <button id="btn" ng-click="test1=test1+1">click me +1</button> </body> </html>
Code
Effect
After clicking twice, these three values are all increased to 2, which seems to be no problem.
Is it really okay? Please see
The view is 2, the model is still 0, synchronization is not achieved, what should I do?
Then the question comes again, which one is better, jquery or angularjs?
Change the code
$('#btn').on('click',function(e) { var scope=angular.element('#dv2').scope();//jquery+angular实现 scope.test2=scope.test2+1;//直接修改test2的值 console.log(scope.test2); $('#dv3').text(Number($('#dv3').text())+1);//纯jquery实现 });
Look again
After clicking twice, the middle one became 1, and the other two became 2.
After clicking 3 times, the middle one changed to 2, but what is the value of scope.test2? Why does it always show one beat slower?
Change it again
$('#btn').on('click',function(e) { var scope=angular.element('#dv2').scope();//jquery+angular实现 scope.test2=scope.test2+1;//直接修改test2的值 scope.$apply();//绑定到视图 console.log(scope.test2); $('#dv3').text(Number($('#dv3').text())+1);//纯jquery实现 });
Look again
Now all three are synchronized. Chinese medicine is good, Western medicine is fast, a combination of Chinese medicine and traditional Chinese medicine! jquery is simple, angularjs is convenient, combine the two...and you're done.
Note: The scope object must call $apply(), otherwise the view and model will be out of sync.
The above is the entire content of this article, I hope you all like it.