Rafael de Castro
Rafael de Castro

Reputation: 1098

AngularJs :: Share data between Views and parameters

I'm creating an App with Ionic Framwork. The Front is ok, and I made the view transitions using $stateProvider.

But I need to do the APP features and other functionalities. I have 2 major problems

1) Pass parameters through href=""

2) Execute some functions after the view transition e when the data is processed show the info on the new View.

Couldn't go further because I'm newbie at Angular and the other examples I searched were not specific. That's what I got so far::

INDEX.HTML

<body ng-controller="AppController as controller">
<ion-view title="View1"><ion-content>
   <a href="#/view2" ng-click="controller.test1">
      <button class="button-style">TEST 1</button>
   </a>
   <a href="#/view2" ng-click="controller.test2">
      <button class="button-style">TEST 2</button>
   </a>
</ion-content></ion-view>
...

View2.HTML

<ion-view title="View2"><ion-content>
   <input type="text" value="{{controller.parameter}}" />
</ion-content></ion-view>

APP.JS

app.config( function($stateProvider, $urlRouterProvider){
    $stateProvider
        .state('view2',{
            url:'/view2',
            templateUrl:'views/view2.html'
    })

...

app.controller('AppController', ['$scope', function($scope){
    parameter = '';
    this.test1 = function(){
        alert('test1');
        parameter = 'One';
    };

    this.test2 = function(){
        alert('test2');
        parameter = 'Two';
    };
}]);

I've tried alot. But now it's just guessing :(

I didn't understand how Controllers and $scope works. I've saw some examples using factory and service, even the CodeSchool (awesome by the way) coudn't help me...

So, any good soul can bring some light here?

Sorry about my misspelled english

Upvotes: 1

Views: 343

Answers (1)

Jia Jian Goi
Jia Jian Goi

Reputation: 1423

First of all, you should be using the ui-sref attribute in your <a> tags (since you're using states, although using href works too), like this:

<a ui-sref="view2"></a>

And if you want to pass parameters, you have to configure your state's url to accept parameters:

url: '/view2/:parameter'

To access parameter in your controller, you'll also need to inject $stateParams into your controller:

app.controller('AppController', function($scope, $stateParams) {

});

And you access parameter via $stateParams.parameter like this:

app.controller('AppController', function($scope, $stateParams) {
    alert($stateParams.parameter);
    $scope.parameter = $stateParams.parameter;
});

Upvotes: 3

Related Questions