简体   繁体   English

在ng-controller中使用$ scope

[英]Using $scope inside ng-controller

using the following code I can't get my parent scope nor the $scope to bind. 使用以下代码,我无法获取父作用域或$ scope进行绑定。

index.html 的index.html

<div ng-controller="MainCtrl">
...
   <div ng-include="sidebarbar.url"></div>
</div>

main.js main.js

angular.module('myApp')
 .controller('MainCtrl', ['$scope', 'DataProvider', 'SidebarService', function ($scope, DataProvider, SidebarService) {
//Initialize
$scope.data= DataProvider;
...

in my index.html inside the controller I have full access to my data scope now I need to display parts of this data inside a sidebar view, SiderbarServices opens the sidebar, sets the slected ID which all works 在控制器内部的index.html中,我可以完全访问我的数据范围,现在我需要在侧边栏视图中显示此数据的一部分,SiderbarServices打开侧边栏,设置所有有效的选定ID

details.html (which is the one opened by ng-include) details.html(由ng-include打开的那个)

<div ng-controller="DetailsCtrl">
    <script type="text/javascript">
    console.log('test'); //is displayed
    console.log(data); //not defined
    console.log($parent); //not defined
    console.log(testScope); //not defined
    </script>
</div>

details.js (controller) details.js(控制器)

angular.module('myApp').controller('DetailsCtrl', ['$scope', function ($scope) {
    $scope.data= $scope.$parent.data;
    $scope.testScope = 'testing if available';

    console.log($scope); //is displayed
    console.log($scope.data); //is displayed
}]);

How can I get access to the data from inside ng-include? 如何从ng-include内部访问数据? (I can't use views as I'm already routing) (我已经在路由,所以无法使用视图)

use this code for details.html: 将此代码用于details.html:

<div ng-controller="DetailsCtrl">
    <!-- <script type="text/javascript">
    console.log('test'); //is displayed
    console.log(data); //not defined
    console.log($parent); //not defined
    console.log(testScope); //not defined
    </script> -->
    <div>{{data}}</div>
</div>

and replace this code in main html: 并在主html中替换此代码:

<div ng-include="'details.html'"></div>

see plunker it is working 看到plunker这是工作

you have done this mistake : it should be ng-include="'details.html'" not ng-include="details.html" 您犯了这个错误:应该是ng-include="'details.html'"而不是ng-include="details.html"

and <script> tag do not work inside ng-controller . <script>标记在ng-controller内不起作用。

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

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