简体   繁体   English

如何在angularjs的控制器外部更改$ scope变量

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

I want to change a $scope.outsidescope outside the controller. 我想在控制器外部更改$scope.outsidescope I am using $routeProvider to route and change controller. 我正在使用$routeProvider来路由和更改控制器。 The $scope.outsidescope is present outside the ng-view . $scope.outsidescope位于ng-view

My Question is How can i change a $scope.value outside of the ng-view . 我的问题是如何在ng-view之外更改$scope.value

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. 使用$ rootScope而不是$ scope在整个应用程序中共享数据。 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 1)绑定$ rootScope中的数据2)绑定服务中的数据

Its not Possible to change $scope outside the controller because it's not available outside the controller. 无法在控制器外部更改$ scope,因为在控制器外部不可用。

If you want to do so you can use parent scope which is $rootScope you can access this anywhere in your application. 如果要这样做,可以使用父范围$ rootScope,您可以在应用程序中的任何位置访问它。

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. 但是根据您的要求,最好使用ng-bind代替expression,并且在路由器中为每个URL都可以调用s resolve来将值分配给this值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM