Bind paired data in object to another element outside ng-repeat - angular

442 Views Asked by At

I have this array of objects that I need to work with:

$scope.pdfs = [
  { "pdf_title": "Corporate Hire", "attached_file": "http://file1.jpg"},
  { "pdf_title": "Wedding Hire", "attached_file": "http://file2.jpg"},
  { "pdf_title": "Filming Hire", "attached_file": "http://file3.jpg"}
];

The pdf_file value is ng-repeated in li's.

What I want to do is if that li is clicked, to push its paired to another div, say the src for an href.

Here are my workings, but not quite correct:

Controller function:

$scope.bindWithFile = function(value) {
            var currentValue = $scope.corpResult = value;

        // pdfs support
        var pdfs = $scope.pdfs;

        for (var i = pdfs.length - 1; i >= 0; i--) {
            if (currentValue == hasOwnProperty(key[pdfs])) {
                value[pdfs] = $scope.corpLinkHref;
            }
        };

Markup:

<div class="w-12" ng-controller="corpHireController">
    <div class="c-6-set">
        <ul>
            <li ng-repeat="pdf in pdfs" class="col-7 link link-inherit" ng-click="bindWithFile(pdf.pdf_title)">{{::pdf.pdf_title}}</li>
        </ul>
    </div>
    <div class="c-6-set">
        <div class="w-12">
            <i class="fs-4 col-7 icon icon-pdf"></i>
        </div>
        <span class="col-7 h4" ng-bind="corpResult"></span>
        <button ng-href="{{::corpLinkHref}}" class="button green2-button smaller-letters full-width">Download</button>
    </div>
</div>

What is needed: Clicking on the titles on the left, binds the pdf_title under the pdf icon and binds the attached_file to the button's href

Clicking on the titles on the left, binds the pdf_title under the pdf icon and binds the attached_file to the button's href

1

There are 1 best solutions below

0
Shaohao On BEST ANSWER

Instead of passing the title of the selected pdf, why not passing the whole object. This way you don't have to performance any find or search function.

Markup:

<div class="w-12" ng-controller="corpHireController">
  <div class="c-6-set">
    <ul>
      <li ng-repeat="pdf in pdfs" class="col-7 link link-inherit" 
          ng-click="bindWithFile(pdf)">
        {{::pdf.pdf_title}}
      </li>
    </ul>
  </div>
  <div class="c-6-set">
    <div class="w-12">
      <i class="fs-4 col-7 icon icon-pdf"></i>
    </div>
    <span class="col-7 h4" ng-bind="corpResult"></span>
    <button ng-href="{{::corpLinkHref}}" 
            class="button green2-button smaller-letters full-width">
      Download
    </button>
  </div>
</div>

Controller

$scope.bindWithFile = function(selectedPdf) {
  $scope.corpResult = selectedPdf.pdf_title;
  $scope.corpLinkHref = selectedPdf.attached_file;
}