简体   繁体   中英

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 ?

您是否尝试过不使用引号'和大括号{{}}

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

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 + ')'}">

Directive ng-click is evaluated by Angular so you don't need to use any braces there. Merge both function calls into one:

$scope.buttonClicked = function(e, img) {
    // e.preventDefault() or whatever
    $scope.selectHash(e);
    $scope.go(img.hashtag);
}

Then in your template use just:

ng-click="buttonClicked($event, img)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM