How to avoid sausage-type binding when using a nested model

I have a nested model and I try to avoid types of situations vm.someObject.someChild.ChildOfChild.name. Is there a way to set the model to external <div>so that I can do ChildOfChild.name or even a name instead. In Silverlight, it was called a DataContext. I put "vm" in the $ scope, but in html I would like not to enter the full path to the attribute.

For instance:

 <div>
    {{someObject.Id}}
    <div>
        {{someObject.name.first}}
        {{someObject.name.last}}
    </div>
     <div>
            {{someObject.someChild.name.first}}
     </div>
 </div>

I would like to do something like this

  <div datacontext = someObject>
    {{Id}}
    <div datacontext = name>
        {{first}}
        {{last}}
    </div>
     <div datacontext = someChild.name>
            {{first}}
     </div>
 </div>
+3
source share
2 answers

You can do this with a custom directive.

HTML:

<div ng-app="myApp" ng-controller="myCtrl as ctrl">
  <div>
      Access from deepObj: {{ctrl.deepObj.one.two.three.four}}
  </div>
  <div scope-context="ctrl.deepObj.one.two.three">
      Access from third level: {{four}}
  </div>
</div>

JS:

var myApp = angular.module('myApp', []);

var myCtrl = function() {
    this.deepObj = {one: {two: {three: {four: "value"}}}};
};

myApp.directive('scopeContext', function () {
    return {
        restrict:'A',
        scope: true,
        link:function (scope, element, attrs) {
            var scopeContext = scope.$eval(attrs.scopeContext);
            angular.extend(scope, scopeContext);
        }
    };
});

For information on what to do scope: true, see the $ compile documentation .

, - data-context, , data-, HTML5.

: http://plnkr.co/edit/rMUQlaNsH8RTWiRrmohx?p=preview

, . . : http://plnkr.co/edit/lCuNMxVaLY4l4k5tzHAn?p=preview

+3

/ ng-init

ng-init, ., , , :

<div ng-init="x = foo.bar.baz">
   {{x.id}}
   {{x.name}}
</div>

BUT , , , ng-model, , .

, ,

, @rob , , , . , , :

  • : n-, ( ), .
  • : ( ), node . *
  • ? Angular, , , .
  • : - Angular, , .
  • ng-model woahs: ng-model . $parent.whatever $parent.$parent.whatever , .

* , $ , : , , .

, jive Angular

, StackOverflow, ATM.... , , , , , , , .

+2

All Articles