Search code examples
javascriptangularjsangularjs-ng-clickangular-servicesng-style

AngularJs - Unable pass object generated by ng-repeat using ng-click


I'm new to Angular, and trying to pass some data on ng-click between controllers using a factory service, based on the data returned from the server and generated by ng-repeat in the front.

This is the HTML:

<div ng-click="go('{{img.hashtag}}')" ng-repeat="img in obj" ng-style="{'background':url({{img.url}})'}">
  <span class="boxName">{{img.hashtag}}</span>
</div>

This works fine:

ng-click="selectHash($event);go('some simple string')"

Whereas this does not:

ng-click="selectHash($event);go('{{img.hashtag}}')"

Since its interpreted as a simple string, and not data extracted from an object.

go function is responsible for navigating to another page and passing the data to the corresponding controller:

$scope.go = function (hash1) {
    $location.path("hash");
    $scope.hashFac = hashFac;
    $scope.hashFac.hash = hash1;
};

The factory service:

appName.factory("hashFac",function(){
    return {

    };
});

How do I extract the data from the img object and send it onwards using ng-click?


Solution

  • You shouldn't be really using {{}} interpolation directive in ng-click & ng-style directive, also while generating background url you should use string concatenation.

    <div ng-click="go(img.hashtag)" ng-repeat="img in obj" 
      ng-style="{'background': 'url(' + img.url + ')'}">