Search code examples
javascriptangularjsscoperootscope

Pass variable value to array arguments in AngularJs 1.X


I'm trying to launch external webpage in my angular application, I am using angular 1.4.X version. I have a array items which will be iterated to display as md-buttons with different icon, names. However i'm interested in adding url (href) to these buttons by passing arguments in the same array.

HTML:

<md-list-item ng-repeat="item in items">
   <div>
        <md-button target="_self" href={{item.url}} class="md-grid-item-content" ng-click="listItemClick($index)" ng-click="showRemedyGridSheet()">
            <md-icon md-svg-src="{{item.icon}}"></md-icon>
            <div class="md-grid-text"> {{ item.name }} </div>
        </md-button>
    </div>
</md-list-item>

JS:
Based on few logic i build url string and assign it to $scope. For example i have used below scenario,

$scope.items = [
    { name: 'Rebook', icon: 'rebook' , url:'rebookUrl'},
    { name: 'Puma', icon: 'puma'},
    { name: 'Nike', icon: 'nike' ,url:'nikeUrl'},
    { name: 'NewBalance', icon: 'nb' ,url:'nbUrl'},
  ];

  //build url
  $scope.rebookUrl= "http://www.reebok.co.uk/";
  $scope.nikeUrl= "http://www.nike.com/us/en_us/";
  $scope.nb="http://au.puma.com/";

How can i pass scope.rebookUrl or $scope.nb values to array $scope.items and then consume them in HTML page to launch to right url upon button click.


Solution

  • Alright after few trial and error i was able to find the solution, I hope it helps others.

    HTML:

    <md-button target="_self" ng-href={{item.url}} class="md-grid-item-content" ng-click="listItemClick($index);showRemedyGridSheet()">
        <md-icon md-svg-src="{{item.icon}}"></md-icon>
        <div class="md-grid-text"> {{ item.name }} </div>
    </md-button>
    

    JS:

    //build url first 
      $scope.rebookUrl= "http://www.reebok.co.uk/";
      $scope.nikeUrl= "http://www.nike.com/us/en_us/";
      $scope.nb="http://au.puma.com/";
    
    // define url arguments in the array 
    $scope.items = [
        { name: 'Rebook', icon: 'rebook' , url:$scope.rebookUrl},
        { name: 'Puma', icon: 'puma'},
        { name: 'Nike', icon: 'nike' ,url:$scope.nikeUrl},
        { name: 'NewBalance', icon: 'nb' ,url:$scope.nbUrl},
      ];
    

    Two thing i noticed, the url argument in an array should be passed with $scope.XXX without any quotes. Second thing was i declared the array first and build the url, so the array url argument wasn't loaded with the values.