简体   繁体   中英

Angularjs: How to pass Scope variables from a view to another view via controller?

I have two views(index1.html and index2.html). In index1, there is a button that pass two parameters into my controller, I need to set these two variables in my scope that index2.html can access them and by clicking on that button the page goes to index2.html,

here is my code:

in Index1.html:

<button type="button" ng-controller="myController" data-ng-click="detailed('title1', 'url1')" class="btn btn-default">test</button>

controller:

app.controller('myController', function ($scope,$filter,$location,$routeParams, myService) {
    $scope.detailed = function(title,url){
        $location.path('/view2');
        return function(){
            $scope.todos = [
                {text: '@title', url: 'url'},
            ];
        }
    };
});

and I get to my index2.html, but nothing gets generated

<div ng-controller="myController">
    <ul>
        <li ng-repeat="todo in todos">
            <span>{{todo.text}}</span>
        </li>
    </ul>
</div>

A nice alternative is to use $routeParams in combination with $location .

app.controller('Index1Controller', function ($scope, $location) {
  $scope.onClick = function () {
   $location.path('index2').search({data: content});
  };
});

app.controller('Index2Controller', function ($scope, $routeParams) {
  console.log($routeParams.data);
});

This will pass data through your URL which will also keep state when you refresh the page. Sites are supposed to capture state via URL, so you can share URLs with people

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