0

I'm learning angulaJS by the video Introduction to Angular.js in 50 Examples , it's awesome but I'm confused since #46. We, say, want to get some nation's information from json file and display it, and we have a directive definition:

countryApp.directive('country', function () {
    return {
        scope: {
            country: '=country'
        },
        restrict: 'A',
        templateUrl: 'country.html'
    };
});

and we invoke the directive country in some html:

<ul>
    <li ng-repeat="country in countries" country="country"></li>
</ul>

My question is: what the exact meaning of 4 different nouns "country" is? the first two in directive scope(country: '=country' ), the last two in html(country="country"). I understand the first one is just a variable definition in directive, so it should be change to another name such as dir_country, but it can't work !

2
  • I suspect the li element is wrapped in a controller? The directive is receiving the country that would have been populated by the parent controller of the element Commented Oct 3, 2015 at 4:00
  • _ - : in attributes are converted to camelCase like dirCountry in angular. Commented Oct 3, 2015 at 8:53

1 Answer 1

1

Here's an example where they are all different:

<li ng-repeat="country in countries" country-dir="country">
.directive("countryDir", function(){
  return {
    scope: {
      countryObj: "=countryDir"
    },
    template: "<span>{{countryObj.name}}</span>",
    link: function(scope){
      console.log(scope.countryObj); // is the bound country object
    }
  };
});

Here:

  • country is an inner scope variable of an item in array of countries
  • country-dir is the directive (which has a normalized form of countryDir).
  • "=countryDir" is a two-way binding to the country-dir attribute (which happens to be the directive itself, but doesn't have to be)
  • countryObj is the internal isolate scope property that is bound to the country object, in case you want the internal name to be different than the attribute. Otherwise, it could have been shortened to countryDir: "=".
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot . the key point is the third one . the scope variable countryObj can take any value passed from any attribute , but in this case happened to be the directive itself . and the directive also happened to be the same name as the scope variable in the original example. after I changed the name of the scope variable , I forget to change the name in the html template named by templateUrl, so it doesn't work.
@eita, not sure I understand your question/issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.