Home > other >  Make a card dynamic with Angular JS
Make a card dynamic with Angular JS

Time:04-14

I have this data in my index.js file:

angular.module('app', [])
.controller('MainCtrl', function($scope) {
  $scope.demos = [ {
    paragrafo: 'richiesta',
    title:'demo1',
    paragrafo2:'dskjdfdjfdfjkdf',
    link: 'https://www.google.it',
    },
    {
    paragrafo: 'richiesta',
    title:'demo2',
    paragrafo2:'dfhfhfjgfkjghfjkgf',
    link: 'https://www.youtube.it',
    },
    {
    paragrafo: 'richiesta',
    title:'demo3',
    paragrafo2:'sjdsdjddfjdf',
    link: 'https://www.sportmediaset.it',
    },
    {
    paragrafo: 'richiesta',
    title:'demo4',
    paragrafo2:'sdjkdhdkjfhdjfh',
    link: 'https://www.elbocon.pe',
    },
    ];
})
.component('card', {
 templateUrl: 'card.html'
 })

in my card.html component i used ng-repeat, i tried iterating it with ng -repeat:

<div ng-repeat="demo in demos">
  <div  style="width: 18rem">
    <div >
      <p>{{demo.paragrafo}}</p>
      <h5 >{{demo.title}}</h5>
      <h6 ></h6>
      <p >{{demo.paragrafo2}}</p>
      <a >{{demo.link}}</a>
    </div>
  </div>
</div>

and in index.html, I put the component in the html index as well:

<body ng-app="app" ng-cloak>
    <div ng-controller="MainCtrl">
      <div >
        <div >
          <div >
            <card></card>
          </div>
        </div>
      </div>
    </div>
  </body>

But it doesn't work, I would like 4 cards with different data to appear, can someone help me?

CodePudding user response:

You need to bind your data to the component. Additionally, accessing that data inside the component requires a reference to $ctrl.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.demos = [{
        paragrafo: 'richiesta',
        title: 'demo1',
        paragrafo2: 'dskjdfdjfdfjkdf',
        link: 'https://www.google.it',
      },
      {
        paragrafo: 'richiesta',
        title: 'demo2',
        paragrafo2: 'dfhfhfjgfkjghfjkgf',
        link: 'https://www.youtube.it',
      },
      {
        paragrafo: 'richiesta',
        title: 'demo3',
        paragrafo2: 'sjdsdjddfjdf',
        link: 'https://www.sportmediaset.it',
      },
      {
        paragrafo: 'richiesta',
        title: 'demo4',
        paragrafo2: 'sdjkdhdkjfhdjfh',
        link: 'https://www.elbocon.pe',
      },
    ];
  }])
  .component('card', {
    bindings: {
      demo: '<'
    },
    template: '<div  style="width: 18rem"><div ><p>{{$ctrl.demo.paragrafo}}</p><h5 >{{$ctrl.demo.title}}</h5><h6 ></h6><p >{{$ctrl.demo.paragrafo2}}</p><a >{{$ctrl.demo.link}}</a></div></div>'
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <card demo="data" ng-repeat="data in demos">
  </card>
</div>

  • Related