ANGULARJS Self-study Road (iii)--Controller and expression

Source: Internet
Author: User

Controller

The role of the controller in ANGULARJS is to enhance the view.
The controller in Angularjs is a function used to add additional functionality to the scope of the view. We use it to set the initial state of the scope object and add custom behavior.
When we create a new controller on the page, Angularjs generates and passes a new $scope to the controller. Scope can be initialized in this controller. Since ANGULARJS is responsible for handling the instantiation of the controller, we only need to write the constructor. The following example shows the controller initialization:

function FirstController($scope) {$scope"hello";}

Careful readers will find that we are creating this function in a global scope. This is not appropriate because it pollutes the global namespace. A more logical way is to create a module and then create a controller in the module, as follows:

var app = angular.module(‘app‘, []);app.controller(‘FirstController‘function($scope) {$scope"hello";});

You can create a custom action that can be used in a view by simply creating a function in the controller scope. Fortunately, Angularjs allows us to invoke functions on the $scope in the same way we call normal data in the view.

With the built-in instruction Ng-click, you can bind any other DOM element, such as a button, link, or a click event. The Ng-click directive binds the MouseUp event in the browser with the event handlers set on the DOM element (for example, when the browser triggers a click event on a DOM element, the function is called). Similar to the previous example, the binding looks like this:

<div ng-controller="Firstcontroller"><h4>The simplest adding machine ever</h4><button ng-click="Add (1)" class="button">Add</button><a ng-click="Subtract (1)" class="button alert"> Subtract</a><h4>Current Count:{{ counter }} </h4></div> 

Both the button and the link are bound to an operation on the internal $scope, and Angularjs will invoke the appropriate method when clicking on any element. Note that when you set which function to call, you pass a parameter (add (1)) with parentheses.
Add an action to Firstcontroller below:

app.controller(‘FirstController‘function($scope) {$scope0;$scopefunction(amount) {$scope.counter += amount; };$scopefunction(amount) {$scope.counter -= amount; };});

The controller can encapsulate the business logic associated with a separate view in a separate container. It is good practice to streamline the controller as much as possible. As a ANGULARJS developer, the use of dependency injection to access the service can accomplish this purpose.

One of the main differences between ANGULARJS and other JavaScript frameworks is that the controller is not suitable for performing DOM operations, formatting or data manipulation, and state maintenance operations other than the storage data model. It's just a bridge between the view and the $scope.

Controller nesting (Scope containment scope)

By default, Angularjs does not find a property in the current scope when it finds it in the parent scope. If Angularjs cannot find the corresponding attribute, it will search up the parent scope until it arrives at $rootscope. If it is not found in Rootscope, the program will continue to run, but the view cannot be updated.

Take a look at this behavior by example. Create a parentcontroller that contains a user object, and then create a Childcontroller to reference the object:

app.controller ( ' Parentcontroller ' , function   ( $scope )  {  $scope . person = {greeted: Span class= "Hljs-keyword" >false };}); App.controller ( ' Childcontroller ' , function   $scope )  {   $scope . SayHello =  function   ()  {  $scope . person.name =  ' Ari Lerner ' ;};});  

If we place the Childcontroller inside the Parentcontroller, the parent scope of the Childcontroller $scope object is the Parentcontroller scope object. Based on the mechanism of the prototype inheritance, we can access the Parentcontroller scope object in the child scope.

For example, we can access the person object defined in Parentcontroller in the DOM element of Childcontroller

<div  ng-controller  = " Parentcontroller ";  <div  ng-controller  =;  <a  ng-click  = "SayHello ()" ;  Say hello</ a ;  </div ;   {{person }}   </div ;    

We see that when you click a button, you can access the value $scope.person in Parentcontroller as if the person object is defined in the scope of the Childcontroller. Childcontroller.

The controller should be as concise as possible, while DOM manipulation and data manipulation in the controller is a bad practice.

Well-designed applications place complex logic in directives and services. By using directives and services, we can make the controller a lightweight and easier to maintain form
Compact Controller:

angular.module(‘myApp‘, []).controller(‘MyController‘function($scope,UserSrv) {// 内容可以被指令控制$scopefunction(user) {UserSrv.runLogin(user);};});
An expression

An example of using an expression has been seen earlier. The notation of binding a variable to $scope with the {{}} symbol is essentially an expression: {{expression}}. When you listen with watch, ANGULARJS will perform operations on the expression or function.
Expressions are very similar to eval (JavaScript), but because expressions are handled by ANGULARJS, they have the following distinct characteristics:

    1. All expressions are executed within the scope to which they belong and have access to the local $scope;
    2. If the expression occurs TypeError and referenceerror do not throw an exception;
    3. No Process Control function (condition control, e.g. If/else) is allowed;
    4. Filters and filter chains can be accepted.

Any action on an expression is executed inside the scope to which it belongs, so that variables that are restricted within the scope can be called inside the expression, and loops, function calls, and apply variables to the mathematical expression medium operation.

Parsing Angularjs expressions

Although Angularjs automatically parses the expression during the run of the $digest loop, it is sometimes useful to parse the expression manually.

ANGULARJS uses this internal service to perform an expression operation that accesses the current scope of the service.

The $parse service is injected into the controller and then invoked to implement a manual parsing of an expression. For example, if there is an input box on the page bound to the expr variable, as follows:

<div  ng-controller  = " Mycontroller ";  <input  ng-model  = type  = "text"  placeholder  =  "Enter An expression" />  < h2 ;   {{ parsevalue }}  </h2 ;  </div ;    

We can set a $watch and parse it in Mycontroller for the expression of expr:

angular.module("myApp", []).controller(‘MyController‘,function($scope,$parse) {$scope.$watch(‘expr‘function(newVal, oldVal, scope) {if (newVal !== oldVal) {// 用该表达式设置parseFunvar$parse(newVal);// 获取经过解析后表达式的值$scope.parsedValue = parseFun(scope);}});});
Interpolation string

In Angularjs, we do have the ability to manually run the template compilation. For example, interpolation allows text strings to be updated in real time based on a condition on the scope.

To do an interpolation operation in a string template, you need to inject the $interpolate service into your object. In the example below, we will inject it into a controller:

angular.module(‘myApp‘, []).controller(‘MyController‘,function($scope$interpolate) {// 我们同时拥有访问$scope和$interpolate服务的权限});

The $interpolate service is a function that can accept three parameters, where the first parameter is required.

    1. Text (String): A string that contains the character interpolation token.
    2. Musthaveexpression (Boolean): If this parameter is set to True, NULL is returned when the passed-in string does not contain an expression.
    3. Trustedcontext (String): Angularjs A strict context escape for a string that has already been interpolated by the $sec.gettrusted () method.

The $interpolate service returns a function that is used to operate the expression in a particular context.
Once these parameters are set, the character interpolation can be done in the controller. For example, suppose we want to make real-time edits in the body of an e-mail message, perform a character interpolation operation when the text changes, and show the results.

 <div ng-controller="Mycontroller"><input  Ng-model="to"type="Email"placeholder="Recipient" />  <textarea ng-model="Emailbody"></textarea ><pre> {{ previewtext }} </pre></div> 

Since the controller has a custom input field that requires the character interpolation to be re-interpolated each time, a $watch is set up to listen for changes in the data.

In short, $watch function monitors a property on a scope. The corresponding function is called as long as the property has changed. You can use the Watch function to run a custom function directly when a property on the scope changes.

In the controller, we set the $watch to monitor the change of the message body and assign the value of the Emailbody property to the Previewtext attribute after the character interpolation.

angular.module ( ' myApp ' , []). Controller ( ' Mycontroller ' ,  function   $scope ,  $interpolate )  { //set listener   $scope .  $watch  ( ' emailbody ' , < Span class= "Hljs-keyword" >function   { if  (body) {var  template =  $interpolate  (body);  $scope . Previewtext =template ({to: . to});};}); In the  

{{to}} can now be used as a variable in the text inside {{Previewtext}}, and the changes to the text are updated in real time.

Use the Startsymbol () method to modify the symbol at the beginning of the identity. This method takes a parameter.

Use the Endsymbol () method to modify the symbol at the end of the identity. This method also accepts a parameter.

If you want to modify the settings of these two symbols, you need to inject $interpolateprovider into the new module when you create it.

Angular.module (' Emailparser ', []). config ([' $interpolateProvider ', function($interpolateProvider) {$interpolateProvider. Startsymbol (' __ ');$interpolateProvider. Endsymbol (' __ ');}]). Factory' Emailparser ', [' $interpolate ', function($interpolate) {//processing of resolved servicesreturn{parse: function(text, context) {varTemplate =$interpolate(text);returnTemplate (context);}};}]);

Now that we have created a module, we can inject it into the app and run the message parser in the text of the message body:

angular.module ( ' myApp ' , [ Span class= "hljs-string" > ' Emailparser ' ]). Controller ( ' Mycontroller ' , [ Span class= "hljs-string" > ' $scope ' ,  ' Emailparser ' , function   ( $scope , Emailparser)  { //set listener   $scope .  $watch  ( ' emailbody ' , function   { if  (body) { $scope . Previewtext = Emailparser.parse (Body, {to:  $scope . to});  
);

Now use the custom __ symbol instead of the {{}} symbol in the default syntax to request interpolated text.
Since we have set the start and end symbols of the expression to __, we need to modify the HTML to replace the {{}} version with this symbol.

<div id="Emaileditor"><input ng-model="to"type="Email"placeholder= "Recipient" /><textarea ng-model="Emailbody"></textarea></div><div id="Emailpreview"><pre>__ Previewtext __</pre></div>

ANGULARJS Self-study Road (iii)--Controller and expression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.