简体   繁体   中英

How to access two controllers AngularJS?

I need to have two instances of a controller. The first instance must set a variable and the second I have to read it. The variable to set is inside the object vm (so do not use $ scope).

The code of controller is:

app.controller("AppController", function(){
    var vm = this;

    vm.search = null;
});

The code of first html page is:

<div class="input-group" ng-controller="AppController as app">
    <input type="text" class="form-control" ng-model="app.search" placeholder="Search...">
</div>

And the code of second html page is:

<div class="input-group" ng-controller="AppController as app">
    {{app.search}}
</div>

But in the second page, the value of app.search is null.

I recommend using a service to communicate data between your controller instances. This answer explains it perfectly.

But if you are keen on not using a service to share data, you can store your search variable in the $rootScope, this will make it available in all your controller instances, and in every other controller in your app. I have to warn you, this is not proper data encapsulation.

Here is how to do it:

First HTML view:

<div class="input-group" ng-controller="AppController as app">
<input type="text" class="form-control" ng-model="$root.search" placeholder="Search...">

Second HTML view:

<div class="input-group" ng-controller="AppController as app">
    {{$root.search}}
</div>

I created this factory:

.factory("search", function(){
    var stringaRicerca = null;
    return {
        getStringa: function(){
            return stringaRicerca;
        }, setStringa: function(stringa){
            stringaRicerca = stringa;
        }
    };
})

And the modified controller is:

app.controller("AppController", function("search"){
    var vm = this;

    vm.string = search.getString;

    vm.set = search.setString;
});

The first page modified is:

<div class="input-group" ng-controller="AppController as app">
    <input type="text" class="form-control" ng-model="search" placeholder="Search...">
    <button class="btn btn-default" ng-click="app.set(search)" type="button">GO!</button>
</div>

And the second page modified is:

<div class="input-group" ng-controller="AppController as app">
    {{app.string}}
</div>

But in the second page i see anything

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