Monday, June 5, 2017

How to connect one model variable to mutiple html elements using angularjs data binding?

@reference_1_stackoverflow
How to connect one model variable to mutiple html elements using angularjs data binding?

@reference_1_toptal
Top 18 Most Common Mistakes that AngularJS Developers Make

Common Mistake #2: Not Having a Dot In There

You probably have read that if you were not having a dot in your ng-model, you were doing it wrong. When it regards inheritance, that statement is often true. Scopes have a prototypal model of inheritance, typical to JavaScript, and nested scopes are common to AngularJS. Many directives create child scopes such as ngRepeat, ngIf, and ngController. When resolving a model, the lookup starts on the current scope and goes through every parent scope, all the way to $rootScope.
But, when setting a new value, what happens depends on what kind of model (variable) we want to change. If the model is a primitive, the child scope will just create a new model. But if the change is to a property of a model object, the lookup on parent scopes will find the referenced object and change its actual property. A new model would not be set on the current scope, so no masking would occur:
function MainController($scope) {
  $scope.foo = 1;
  $scope.bar = {innerProperty: 2};
}

angular.module(‘myApp’, [])
.controller('MainController', MainController);
<div ng-controller=“MainController">
  <p>OUTER SCOPE:</p>
  <p>{{ foo }}</p>
  <p>{{ bar.innerProperty }}</p>
  <div ng-if=“foo”> <!— ng-if creates a new scope —>
    <p>INNER SCOPE</p>
    <p>{{ foo }}</p>
    <p>{{ bar.innerProperty }}</p>
    <button ng-click="foo = 2”>Set primitive</button>
    <button ng-click=“bar.innerProperty = 3”>Mutate object</button>
  </div>
</div>
Clicking the button labelled “Set primitive” will set foo in the inner scope to 2, but will not change foo in the outer scope.
Clicking the button labelled “Change object” will change the bar property from the parent scope. Since there is no variable on the inner scope, no shadowing will happen, and the visible value for bar will be 3 in both scopes.
Another way to do this is to leverage the fact that the parent scopes and the root Scope are referenced from every scope. The $parent and $root objects can be used to access the parent scope and $rootScope, respectively, directly from the view. It may be a powerful way, but I am not a fan of it due to the problem with targeting a particular scope up the stream. There is another way to set and access properties specific to a scope - using the controllerAs syntax.


@reference_3_itfashion4u
 AnularJS 'limitTo' filter inside/outside div element with 'ng-if' attribute

No comments:

Post a Comment