2

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?

3 Answers 3

2

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 + ')'}">
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, now the click works as needed. I tried removing the curly braces from img.url but I get an error GET http://localhost/project/img.url 404 (Not Found)
2

Have you tried without quotes ' and curly braces {{}}:

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

Comments

1

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)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.