[英]Update main page from views inside ngview in AngularJS
I have a AngularJS SPA application. 我有一个AngularJS SPA应用程序。 The main page includes an ng-view directive and a textbox with ng-model bind.
主页包括ng-view指令和带有ng-model绑定的文本框。 I have some views that display inside ng-view.
我有一些显示在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. 我更新了ngview中加载的view内部的counterResult。 I want the counterResult get updated.
我希望counterResult得到更新。
so you want to access a value from outside of the ng-view scope, in the inside of the ng-view scope. 因此,您想从ng-view范围内的ng-view范围之外访问值。 check this code, which I've tested on jsbin and it works fine:
检查此代码,该代码已在jsbin上测试过,并且工作正常:
index.html: 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: 以及必须在index.html文件中添加的app.js文件:
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. 在您的testController范围中,您要定义countResult值,该值将不在另一个不是从testController继承的范围中找到。 Here you ng-view isn't child of testController so it won't get the value of countResult.
在这里,您的ng-view不是testController的子级,因此它不会获得countResult的值。 So here you can put you countResult value in the $rootScope.
因此,在这里您可以将countResult值放入$ rootScope中。 As all $scope are children of $rootScope it will get the value in side the ng-view.
由于所有$ scope都是$ rootScope的子级,因此它将在ng-view中获得值。 Hope the explanation make sense.
希望解释有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.