Search code examples
angularjsangularjs-components

Simple Hello World using Angularjs components


This is my first attempt at angularJs components so please have patience. Any ideas why it would not print Hello World?

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

script.js

(function () {

  'use strict';

    angular
         .module('myApp', [])
         .component('sampleComponent', {
             template: '<h1>Hello {{$ctrl.name}}!</h1>',
             bindings: {
                 name: '<'
             },
             controller: function () {
               //alert('here');
             }
         });

})();

index.html

<!DOCTYPE html>
<html>
  <head>
    <script data-require="[email protected]" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="[email protected]" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-app="myApp">
     <sample-component name="World"></sample-component>  
  </body>
</html>

Solution

  • You're using '<' for your binding. This means that when passing name="World", World is supposed to be an Angular expression, whose value is passed to the component. Since you have no World variable in the root scope, it's undefined, and an empty string is thus displayed.

    Use '@' for your binding, or use name="'World'".