How does data binding work in AngularJS?

前端 未结 14 1540
情话喂你
情话喂你 2020-11-21 05:41

How does data binding work in the AngularJS framework?

I haven\'t found technical details on their site. It\'s more or less clear how it works when data

相关标签:
14条回答
  • 2020-11-21 05:54

    AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

    The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

    To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

    Issues with change listeners:

    • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
    • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
    • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

    What about performance?

    So it may seem that we are slow, since dirty-checking is inefficient. This is where we need to look at real numbers rather than just have theoretical arguments, but first let's define some constraints.

    Humans are:

    • Slow — Anything faster than 50 ms is imperceptible to humans and thus can be considered as "instant".

    • Limited — You can't really show more than about 2000 pieces of information to a human on a single page. Anything more than that is really bad UI, and humans can't process this anyway.

    So the real question is this: How many comparisons can you do on a browser in 50 ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6 ms. On Internet Explorer 8 it takes about 40 ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

    It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

    0 讨论(0)
  • data binding:

    What is data binding?

    Whenever the user changes the data in the view , there occurs an update of that change in the scope model, and viceversa.

    How is it possible?

    Short answer : With the help of digest cycle.

    Description : Angular js sets the watcher on the scope model, which fires the listener function if there is a change in the model.

    $scope.$watch('modelVar' , function(newValue,oldValue){
    

    //Dom update code with new value

    });

    So When and How is the watcher function called?

    Watcher function is called as part of the digest cycle.

    Digest cycle is called automatically triggered as part of angular js built in directives/services like ng-model , ng-bind , $timeout, ng-click and others.. that let you trigger the digest cycle.

    Digest cycle function:

    $scope.$digest() -> digest cycle against the current scope.
    $scope.$apply() -> digest cycle against the parent scope 
    

    i.e$rootScope.$apply()

    Note: $apply() is equal to $rootScope.$digest() this means the dirty checking starts right from the root or top or the parent scope down to all the child $scopes in the angular js application.

    The above features work in the browsers IE for the mentioned versions also just by making sure your application is angular js application which means you are using the angularjs framework script file referenced in the script tag.

    Thank you.

    0 讨论(0)
  • 2020-11-21 05:59

    It happened that I needed to link a data model of a person with a form, what I did was a direct mapping of the data with the form.

    For example if the model had something like:

    $scope.model.people.name
    

    The control input of the form:

    <input type="text" name="namePeople" model="model.people.name">
    

    That way if you modify the value of the object controller, this will be reflected automatically in the view.

    An example where I passed the model is updated from server data is when you ask for a zip code and zip code based on written loads a list of colonies and cities associated with that view, and by default set the first value with the user. And this I worked very well, what does happen, is that angularJS sometimes takes a few seconds to refresh the model, to do this you can put a spinner while displaying the data.

    0 讨论(0)
  • 2020-11-21 06:01

    AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

    $watch() :-

    This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

    $digest() -

    This function iterates through all the watches in the $scope object, and its child $scope objects
    (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

    $apply() -

    Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

    0 讨论(0)
  • 2020-11-21 06:02
    1. The one-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. It is used in classical template systems. These systems bind data in only one direction.

    2. Data-binding in Angular apps is the automatic synchronisation of data between the model and view components.

    Data binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. If the model is changed, the view reflects the change and vice versa.

    0 讨论(0)
  • 2020-11-21 06:03

    AngularJs supports Two way data-binding.
    Means you can access data View -> Controller & Controller -> View

    For Ex.

    1)

    // If $scope have some value in Controller. 
    $scope.name = "Peter";
    
    // HTML
    <div> {{ name }} </div>
    

    O/P

    Peter
    

    You can bind data in ng-model Like:-
    2)

    <input ng-model="name" />
    
    <div> {{ name }} </div>
    

    Here in above example whatever input user will give, It will be visible in <div> tag.

    If want to bind input from html to controller:-
    3)

    <form name="myForm" ng-submit="registration()">
       <label> Name </lbel>
       <input ng-model="name" />
    </form>
    

    Here if you want to use input name in the controller then,

    $scope.name = {};
    
    $scope.registration = function() {
       console.log("You will get the name here ", $scope.name);
    };
    

    ng-model binds our view and render it in expression {{ }}.
    ng-model is the data which is shown to the user in the view and with which the user interacts.
    So it is easy to bind data in AngularJs.

    0 讨论(0)
提交回复
热议问题