luke luke - 3 months ago 14
Javascript Question

Use data in view from controller from ng-click angular

Pretty new to angular and having a little trouble getting data from controller and displaying in view using ionic.

I have a function in a controller ('DashCtrl') where I pass through a string to use within the function by using ng-click. For now I just want to take this string and display it in the next view as I have an href on the same element I have the ng-click event.

When I log the string on the next page, it is working and shows up. How do I get to use this in the view?

Heres the code:

HTML

*first page

<ul contentful-entries>
<div ng-repeat="story in $contentfulEntries.items">
<li class="story col col-100">
<a href="#/tab/story/{{story.fields.slug}}" ng-click='storyDetails("{{story.fields.title}}")'>
<p>{{ story.fields.title }}</p>
</a>
</li>
</div>
</ul>


*redirects to this on the ng-click

<ion-view view-title="Story">
<ion-nav-buttons side="left">
<button class="button back-button buttons button-clear header-item" ng-click="goBack()">
<i class="icon ion-ios-arrow-back"> Back</i>
</button>
</ion-nav-buttons>
<ion-content>
<ion-list ng-controller="DashCtrl">
<h1>{{ story.slug }} </h1>
<p> <!-- HERE IS WHERE I WANT TO DISPLAY THE STRING --> </p>
</ion-list>
</ion-content>
</ion-view>


*heres my controller

.controller('DashCtrl', function($scope, $stateParams, $ionicHistory) {

$scope.storyDetails = function($scope, details) {
// here is the data i need to display in the view
// the console.log shows up in the browser
console.log(details);
}

$scope.goBack = function(){
$ionicHistory.goBack();
}

// this is working fine
$scope.story = $stateParams;
})

Answer

I ended up using the $rootScope. I know this may not be the best solution but I am just trying to grasp Angular at the moment.

In my controller I used

.controller('DashCtrl', function($scope, $stateParams, $rootScope, $ionicHistory) {

  $scope.goBack = function(){
    $ionicHistory.goBack();
  }

  $scope.storyDetails = function(details) {
    $rootScope.details = details;
    return $rootScope.details;
  }
})

Then I am able to use the $rootScope.details in another controller to use in a function I need the string for.

I know I'm not doing this the Angular way, so if anyone would be kind enough to show me how to do this 'properly' without using the rootScope, I'd be forever in your debt.