简体   繁体   中英

How to bind any patricular object property in angular component

I am new to angular 1.6 component architecture and having a simple problem. I am having one src object with having two properties within it ie name and age . Now, what I want is binding that name property in html.

The following is the code:

test.js:-

$ctrl.src = {
    details: [
      { Id: 1, Name: "Test1", Address: "Add1" },
      { Id: 2, Name: "Test2", Address: "Add2" }
    ]
  };

test.html:-

    <cell-component>Hi {{Name}}</cell-component>


Expected Output:-

    Hi test

Since $scope.src refers to a object with two properties, angular model binding always requires to specify the object key in the view together with the object name like this

  {{src.Name}} //renders $scope.src.Name
  {{src.Age}} //renders $scope.src.Age

So your view needs to be changed to

<cell-component>Hi {{src.Name}}</cell-component>

There is also another way to access the properties and render them in view.

  {{src['Name']}} //renders $scope.src.Name
  {{src['Age']}} //renders $scope.src.Age

Which leads to

 <cell-component>Hi {{src['Name']}}</cell-component>

When you need to access the properties of particular object, You shoulse use dot operator like below

<cell-component>Hi {{src.Name}}</cell-component>

EDIT

With your modification details is an array where you need to specify the index you want to display

 <cell-component>Hi {{src.details[0].Name}}</cell-component>

one simple thing you can do is you just have to put ng-repeate on src.details and print each object in it. ie <div ng-repeate="obj in src.details"><div>{{obj.Name}}</div> </div>

First you have to take the src object on scope to get it into view as expression.

'src' is an object having property named 'details' which itself is an array of objects. So you have to go down according to the object hierarchy to get the value of property 'Name'. But 'Name' is an property under 'details' which is an array so you must iterate over it using ng-repeat or simply specify the array index.

 var app = angular.module('app',[]); app.controller('ctrl', function($scope){ $scope.src = { details: [ { Id: 1, Name: "Test1", Address: "Add1" }, { Id: 2, Name: "Test2", Address: "Add2" } ] }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="ctrl"> <h3>Hi {{src.details[0].Name}}</h3> <h3>Hi {{src.details[1].Name}}</h3> <h3 ng-repeat="obj in src.details">Hi {{obj.Name}}</h3> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM