AngualrJS is a very considerate web application framework. It has very good official documentation and examples; after testing the famous TodoMVC project in a real environment, it stands out among a large number of frameworks; and there are very good demonstrations or displays everywhere on the Internet. But for a developer who has never been exposed to a framework similar to AngularJS and who almost always uses JavaScript libraries like jQuery, it is a bit difficult to switch from jQuery thinking to AngularJS thinking. At least this is the case for me, so I want to share some study notes in the hope of helping some developers.
This article uses jQuery and Angular to implement the same instance, so as to experience the differences between the two and the charm of AngularJS.
First of all, of course, you need to reference the jquery.js and angular.js files.
■ Use jQuery to write a simple click event
<button id="jquery-button">JQuery Button</button> <div id="jquery-content">I am jquery content</div> $(function(){ $("#jquery-button").click(function(){ $('#jquery-content').toggle(); }) })
What if we want more divs to toggle through the same click event?
--首先要在页面中添加div,然后在js中添加相应的代码 <button id="jquery-button">JQuery Button</button> <div id="jquery-content">I am jquery content</div> <div id="jquery-content1">I am jquery content1</div> $(function(){ $("#jquery-button").click(function(){ $('#jquery-content').toggle(); $('#jquery-content1').toggle(); }) })
What is the situation like in AngularJS?
■ Use Angular to write a simple click event
<div ng-app="app" ng-controller="AppCtrl as app"> <button ng-click="app.toggle()">Angular Button</button> <div ng-hide="app.isHidden">Angular content</div> </div> var app = angular.module("app",[]); app.controller("AppCtrl", function(){ var app = this; app.isHidden = false; app.toggle = function(){ app.isHidden = !app.isHidden; } })
What if we want more divs to toggle through the same click event?
--我们只要在页面中添加一个div,通过ng-hide属性来声明 <div ng-app="app" ng-controller="AppCtrl as app"> <button ng-click="app.toggle()">Angular Button</button> <div ng-hide="app.isHidden">Angular content</div> <div ng-hide="app.isHidden">Angular content1</div> </div>
Above, through a simple example to compare the differences between jQuery and Angular, we can find that: AngularJS responds to changes through declarations. Compared with jQuery, AngularJS responds to changes at a lower cost and is more flexible.