简体   繁体   中英

How to change a $scope variable outside the controller in angularjs

I want to change a $scope.outsidescope outside the controller. I am using $routeProvider to route and change controller. The $scope.outsidescope is present outside the ng-view .

My Question is How can i change a $scope.value outside of the ng-view .

Sample Code:

<html ng-app="Myapp">
 .......
<body>
   <div>
     {{outsidescope}}
   </div>
   <div class="" data-ng-view></div>
</body>
</html>

Angular Code:

var app = angular.module('Myapp', ['ngRoute']).
   config(['$routeProvider', function($routeProvider) {
   $routeProvider
    .when("/", {templateUrl: "partials/home4.html", controller: "PageCtrl"})
    .otherwise({
        redirectTo: '/pages/404'
     })
 }]);

app.controller('PageCtrl', ['$cookies',function ($scope) {
   $scope.outsidescope = 'Some thing.';
}

Use $rootScope instead of $scope to share data across the application. But creating a custom service is the best approach.

There are only two ways to share data between controllers

1) Binding data in $rootScope 2) Binding data in services

Its not Possible to change $scope outside the controller because it's not available outside the controller.

If you want to do so you can use parent scope which is $rootScope you can access this anywhere in your application.

But As per you requirement its better to use ng-bind instead of expression and in your router for every url you can call s resolve to assign the value to your this value.

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