luke luke - 6 months ago 34
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:


*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>

*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>
<ion-list ng-controller="DashCtrl">
<h1>{{ story.slug }} </h1>

*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

$scope.goBack = function(){

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


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(){

  $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.