javascript - How to use an attribute in a directive to select data -


i'm trying make directive-element uses value of attribute make http request , prints response. part of using value of attribute make http request covered using $attrs in controller associated directive. however, if i'm trying output data 3 different attribute values in same document, directives output same data.

i have made plunker of code demonstrate problem

basically want this:

<person personnumber='person1'></person> <person personnumber='person2'></person> <person personnumber='person3'></person> 

my data example.com/{person-number}:

person 1:

 {    name: "john",    city: "new york"  } 

person 2:

 {       name: "bob",       city: "los angeles"  } 

person 3:

 {       name: "jay",       city: "san diego"  } 

wanted output:

john: new york  bob: los angeles  jay: san diego 

what get:

jay: san diego  jay: san diego  jay: san diego 

what see values have changed last http request. don't know how fix this.

here angular code (also visible in plunker):

var app = angular.module('app', []);  app.controller('personcontroller', ['$scope', '$attrs', function($scope, $attrs) {     //mock json response     var people = {       person1: {         name: "john",         city: "new york"       },       person2: {         name: "bob",         city: "los angeles"       },       person3: {         name: "jay",         city: "san diego"       }     };      //mock $http.get api url (www.example.com/{person})     var self = this;     function mockhttpgetservice() {       self.info = people[$attrs.personnumber];     }     mockhttpgetservice();   } ]);  app.directive('person', function() {     return {       restrict: 'e',       templateurl: 'template.html',       controller: 'personcontroller',       controlleras: 'person'     };   } ); 

and template:

<p>{{person.info.name}}: {{person.info.city}} </p> 

question

i think might have "scope" property of directive, have tried different versions ('=', '@', '<', '&'), not able work.

could please me?

you correct in assumption has scope property in directive. need make work:

{   restrict: 'e',   templateurl: 'template.html',   controller: 'personcontroller',   controlleras: 'person',   scope: {     personnumber:'='   } };  

updated plunker - https://plnkr.co/edit/i4anasjssq8ikggho7ek?p=preview

the reason failing before adding scope property directive descriptor, scope of surrounding template directive declared. since it's sharing scope among instances of directive, last 1 assigned assigned of them. in case person3 got assigned last person-number therefore 3 instances looking @ original scope's person-number value.

isolate scope happens when assign object scope. in case i've assigned new scope personnumber. unique scope per instance of directive.


Comments