简体   繁体   中英

Update main page from views inside ngview in AngularJS

I have a AngularJS SPA application. The main page includes an ng-view directive and a textbox with ng-model bind. I have some views that display inside ng-view. I have a variable is shared between these views so I used a service for that. My Issue is when I click a button inside the views this variable changed. I want to display the changed value inside the textbox in main page as soon as it changed. My Code is As below:

 <div data-ng-app="demoApp">
    <div ng-controller="testController">
        {{countResult}}
    </div>
    <ng-view class="content"></ng-view>
</div>

I update counterResult inside view which is loaded in ngview. I want the counterResult get updated.

so you want to access a value from outside of the ng-view scope, in the inside of the ng-view scope. check this code, which I've tested on jsbin and it works fine:

index.html:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
   <div data-ng-app="demoApp" ng-init="data.countResult='test'">
    <div ng-controller="testController">
        Outside ng-view: {{data.countResult}} <br>
    </div>
    <ng-view class="content"></ng-view>
</div>

</body>
</html>

and your app.js file which you have to add in index.html file:

angular.module('demoApp', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider
        .when('/', {
            template: '<div>Inside ng-view: {{data.countResult}}<br><input ng-model="data.countResult"/></div>',
            controller: 'viewMainController'
        })
        .otherwise({
            redirectTo: '/'
        });                    
    }])
    .controller('testController', ['$scope','$rootScope', function($scope, $rootScope){

    }])
    .controller('viewMainController', function($scope){

    });

Here in your testController scope you're defining the countResult value which will not be found in another scope that isn't prototypically inherited from testController. Here you ng-view isn't child of testController so it won't get the value of countResult. So here you can put you countResult value in the $rootScope. As all $scope are children of $rootScope it will get the value in side the ng-view. Hope the explanation make sense.

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