AngularJS

William Shakespeare
William ShakespeareOriginal
2025-02-23 10:44:11295browse

AngularJS

Core points

  • AngularJS, a JavaScript framework developed by Google, allows developers to create front-end code without having to directly manipulate the Document Object Model (DOM). This can be achieved by defining dynamic views and controllers using instructions and data binding.
  • AngularJS uses MVC (Model-View-Controller) structure. The model is defined by Angular modules and controllers that are connected to HTML via instructions. This allows for two-way data binding, where changes in the model automatically update the view and vice versa.
  • In AngularJS, directives extend HTML's vocabulary, providing more dynamic and powerful templates. Examples include ng-repeat for iterating the set, ng-click for event processing, and ng-show for conditional rendering.
  • Although AngularJS has received some criticism for learning curves and the use of non-standard HTML attributes, it provides a unique approach to web development that encourages the creation of more composable, testable applications. Separating design concerns with MVC reduces the amount of code needed to connect components.

AngularJS quickly became one of the most popular JavaScript frameworks with its advanced philosophy. With Google's support and development, AngularJS's approach to front-end might seem a bit weird at first, but you'll soon wonder why you used other approaches before. AngularJS enables developers to write front-end code without having to directly manipulate the DOM. This tutorial will guide you through the process by building an application that defines dynamic views and controllers using directives and data binding. If you are familiar with CoffeeScript (not required by AngularJS), you will be more interested in this article, but mastering the basics of JavaScript is enough. You may have seen a lot of to-do apps before, so let's build something interesting – tic toe! We will start with the marking board. AngularJS claims to extend HTML's vocabulary instead of hiding DOM behind JavaScript. The idea is that HTML itself is pretty good, but we can add some elements and attributes to build a powerful, dynamic template language you are already familiar with. Our board is just a simple table. If we program with good desire, we really just need to iterate over the board and output one cell for each cell. The actual code is very close to our idea:

<code class="language-html"><table>
  <tr ng-repeat="row in board.grid">
    <td ng-repeat="cell in row">
      {{ cell.marker }}
    </td>
  </tr>
</table></code>

Wait, what are those weird ng elements and beard brackets? Let's take a step back and take it step by step.

<tr ng-repeat="row in board.grid">
<p></p>
<h2>AngularJS command</h2>
<p><code>ng-repeat is an  directive  of AngularJS and is one of the HTML extensions provided. It allows us to iterate over the collection and instantiate the template for each project. In this example, we tell AngularJS to repeat each line in the board property of the grid object. Suppose <tr> is a two-dimensional array, and <code>grid is an object on the window. board
<code class="language-html"><table>
  <tr ng-repeat="row in board.grid">
    <td ng-repeat="cell in row">
      {{ cell.marker }}
    </td>
  </tr>
</table></code>

Then, we iterate over the cells in the row using another ng-repeat directive. The double braces here indicate that an expression using AngularJS data binding -- The content of <td> will be replaced with the <code>marker attribute of the corresponding cell.

So far, it's very simple, right? You can immediately understand what the generated tag will look like. We don't need to use heavyweight tools like jQuery to create new elements and fill them, we just need to clarify our templates. This is easier to maintain – we just look at the HTML to know exactly how the DOM will change without tracking down some vague JavaScript code we don't actually remember writing.

Now we can visualize the state of the board, and we will provide it with a data source by defining the actual content of board.

<code class="language-html"><tr ng-repeat="row in board.grid">
<p>We first add some JavaScript code to define an AngularJS module for our application. The first parameter is the name of the application, <code>['ng']</code> means we need the "ng" module of AngularJS, which provides the core AngularJS service. </p>
<p>We adjust HTML to use the <code>ng-app</code> directive instructs us to use our application module. </p>
<pre class="brush:php;toolbar:false"><code class="language-html"><td ng-repeat="cell in row">
  {{ cell.marker }}
</td></code>

MVC - Define controllers and views

The MVC feature of AngularJS comes into play here. We add some JS code to call the controller function on our newly created application module, passing the name of the controller and the function that implements it.

<code class="language-javascript">app = angular.module('ngOughts', ['ng'])</code>

In this case, our controller function accepts a parameter $scope, which is the dependency of our controller. AngularJS uses dependency injection to provide us with this service object, inferring the correct object from the name of the function parameter (there is also an alternative syntax that also allows minification).

We now add a ng-controller directive to the HTML template to connect it to our controller:

<code class="language-html"><div ng-app="ngOughts">
<p>Same, it's as simple as a property with a controller name. Interesting things happen here - elements nested inside our body tags are now accessible to the <code>$scope</code> service object. Our <code>ng-repeat</code> property will then look for the <code>BoardCtrl</code> variable within the scope of <code>board</code>, so let's define it: </p>
<pre class="brush:php;toolbar:false"><code class="language-javascript">app.controller "BoardCtrl", ($scope) -></code>

We are making some progress now. We inject Board into our controller, instantiate it and make it available within the scope of BoardCtrl .

Let's go ahead and implement a simple Board class.

<code class="language-html"><div ng-controller="BoardCtrl">
  <table>
    <tr ng-repeat="row in board.grid">
      ...
    </tr>
  </table>
</div></code>

Add factory

We can then define a factory which only returns the Board class, allowing it to be injected into our controller.

<code class="language-javascript">app.controller "BoardCtrl", ($scope, Board) ->
    $scope.board = new Board</code>

can be defined directly within the factory function, and even put Board on the window object, but keeping it independent here allows us to test Board independently of AngularJS and encourage reusability. Board

So now we have an empty chessboard. Exciting stuff, right? Let's set it up so that clicking a cell will place a mark there.

<code class="language-html"><table>
  <tr ng-repeat="row in board.grid">
    <td ng-repeat="cell in row">
      {{ cell.marker }}
    </td>
  </tr>
</table></code>

We added a <td> directive to each <code>ng-click element. When we click a table cell, we will call the board function on playCell using the clicked cell object. Fill Board Implementation:

<code class="language-html"><tr ng-repeat="row in board.grid">
<p></p>
<h2>Bidirectional data binding</h2>
<p>Okay, so now that we have updated the board model, we need to update the view, right? </p>
<p>No! AngularJS data binding is <em>Bidirectional </em>—It observes changes in models and propagates them back to the view. Similarly, updating the view will update the corresponding model. Our tags will be updated in our <code>Board</code> internal grid, and the content of <code><td> will be changed immediately to reflect this. 
<p> This eliminates a lot of fragile, selector-dependent boilerplate code you had to write before. You can focus on application logic and behavior rather than pipelines. </p>
<p>It would be great if we knew someone would win. Let's implement it. We will omit the code that checks the winning criteria here, but it exists in the final code. Suppose when we find the winner, we will set the winning attribute on each cell that makes up the winner. </p>
<p> Then we can change our <code><td> to something like this: 
<pre class="brush:php;toolbar:false"><code class="language-html"><td ng-repeat="cell in row">
  {{ cell.marker }}
</td></code>
<code class="language-javascript">app = angular.module('ngOughts', ['ng'])</code>

If winning is true, ng-class will apply the "winning" CSS class to <td>, let's set a pleasant green background to celebrate our victory. You said you'll have another game? We need a reset board button: <pre class="brush:php;toolbar:false">&lt;code class=&quot;language-html&quot;&gt;&lt;div ng-app=&quot;ngOughts&quot;&gt; &lt;p&gt;Add it to our controller and we will call &lt;code&gt;reset&lt;/code&gt; when the button is clicked. The board marker will be cleared, all CSS classes will be cleared, and we are ready to start again - no need for us to update the DOM element. &lt;/p&gt; &lt;p&gt;Let us really show off our victory: &lt;/p&gt; &lt;pre class=&quot;brush:php;toolbar:false&quot;&gt;&lt;code class=&quot;language-javascript&quot;&gt;app.controller &quot;BoardCtrl&quot;, ($scope) -&gt;&lt;/code&gt;</pre> The <p><code>ng-show command allows us to conditionally display the <h1></h1> element when the game wins, and data binding allows us to insert the winner's tag. Simple and expressive.

Add to be easier to combine and easier to test

It is worth noting that most of our code deals with plain old JavaScript code. This is intentional - not extending framework objects, just writing and calling JS code. This approach helps create applications that are easier to combine and easier to test, which feel lightweight. Our design concerns are separated by MVC, but we don't need to write a lot of code to connect them together.

However, AngularJS is not without limitations. Many complain about official documentation and the relatively steep learning curve, some worry about SEO, and others just hate using non-standard HTML attributes and elements.

However, there are solutions to these problems, and AngularJS's unique approach to web development is definitely worth the time to explore.

You can view the actual effect of the final code on Plunkr, or download it from GitHub.

Comments in this article have been closed. Have questions about AngularJS? Why not ask questions on our forum?

FAQs about AngularJS directives and data binding

What is the difference between AngularJS directives and components?

AngularJS directives and components are powerful features of the AngularJS framework. Directives allow you to create reusable custom HTML elements and properties, while components are special directives that use simpler configurations. Components are suitable for building component-based application structures, which are more modern and widely used in front-end development today. However, the instructions are more flexible and can operate the DOM directly, which components cannot do.

How does data binding in AngularJS work?

Data binding in AngularJS is the automatic synchronization of data between model and view components. AngularJS implements data binding in a way that allows you to treat your model as a single source of facts in your application. The view is always a projection of the model. When the model changes, the view reflects the change and vice versa.

Can you explain the difference between one-way data binding and two-way data binding?

One-way data binding is the simple flow of data from a model to a view or from a view to a model. This means that if the model state changes, the view will not be updated. On the other hand, bidirectional data binding means that if the model state changes, the view will be updated; if the view changes (such as due to user interaction), the model state will be updated. This allows for real-time effects, which means changes (such as user input) will be immediately reflected in the model state.

How to create custom directives in AngularJS?

To create custom directives in AngularJS, you need to use the .directive function. You can name your directive and then create a factory function that will save all directive options. The factory function is injected using a dependency (if any), and then it returns an object that defines directive options.

What is the scope of isolation in AngularJS directive?

The isolation scope in AngularJS directive allows you to create a new scope for the directive. This means that any changes in the directive scope will not affect the parent scope and vice versa. This is very useful when you want to create reusable and modular components.

How to use transcription in AngularJS directive?

Transcription is a feature in AngularJS that allows you to insert custom content into instructions. By setting the transclude option to true in the directive definition object, you can use the ng-transclude directive to insert custom content in the directive template.

What is the link function in the AngularJS directive?

The link function is used for AngularJS directives to manipulate the DOM or add an event listener. It is executed after cloning the template. This function is usually used to perform tasks such as setting DOM event handlers, monitoring changes in model properties, and updating DOM.

How to use controller functions in AngularJS directives?

The controller function is a JavaScript constructor used to enhance AngularJS scope. When the controller is attached to the DOM via the ng-controller directive, AngularJS instantiates a new controller object using the specified controller's constructor. A new subscope will be created and provided to the controller as an injectable parameter as a constructor $scope.

What is the difference between "@", "=", and "&" in the directive scope options?

These symbols are used to bind data to the instruction scope. "@" is used for string binding, "=" is used for bidirectional model binding, and "&" is used for method binding. They allow you to isolate scopes, making your instructions more modular and reusable.

How to test my AngularJS directive?

AngularJS provides a module called ngMock that allows you to inject and mock AngularJS services in unit tests. You can use it to test your instructions. You can also use other testing frameworks like Jasmine or Mocha with ngMock to write and run tests.

The above is the detailed content of AngularJS. For more information, please follow other related articles on the PHP Chinese website!

JavaScript mvc jquery css html angular coffeescript 构造函数 字符串 class JS 对象 作用域 事件 dom 选择器 github SEO
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Ajax-Zoom ReviewNext article:Ajax-Zoom Review

Related articles

See more