gpt4 book ai didi

javascript - 从 AngularJS 中 ngview 内的 View 更新主页

转载 作者:行者123 更新时间:2023-12-02 16:21:30 25 4
gpt4 key购买 nike

我有一个 AngularJS SPA 应用程序。主页包括一个 ng-view 指令和一个带有 ng-model 绑定(bind)的文本框。我有一些显示在 ng-view 内的 View 。我有一个变量在这些 View 之间共享,所以我为此使用了一个服务。我的问题是,当我单击 View 内的按钮时,此变量发生了变化。我想在更改后立即在主页的文本框中显示更改后的值。我的代码如下:

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

我在 ngview 中加载的 View 内更新 counterResult。我希望 counterResult 得到更新。

最佳答案

所以你想从 ng-view 范围之外、在 ng-view 范围内部访问一个值。检查这段代码,我已经在 jsbin 上测试过它并且工作正常:

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>

以及您必须在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){

});

在您的 testController 作用域中,您定义了 countResult 值,该值在不是从 testController 原型(prototype)继承的另一个作用域中找不到。在这里,您的 ng-view 不是 testController 的子级,因此它不会获取 countResult 的值。因此,您可以将 countResult 值放入 $rootScope 中。由于所有 $scope 都是 $rootScope 的子级,因此它将获取 ng-view 中的值。希望解释能有意义。

关于javascript - 从 AngularJS 中 ngview 内的 View 更新主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29070228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com