在ng-controller中使用$ scope

时间:2014-11-08 13:33:51

标签: javascript angularjs

使用以下代码,我无法获取父作用域,也无法获取要绑定的$ scope。

的index.html

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

main.js

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

在控制器内的index.html中我现在可以完全访问我的数据范围我需要在侧边栏视图中显示部分数据,SiderbarServices打开侧边栏,设置所有工作的选定ID

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(控制器)

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
}]);

如何从ng-include内部访问数据? (我不能使用视图,因为我已经路由了)

1 个答案:

答案 0 :(得分:1)

将此代码用于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>

并在主html中替换此代码:

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

请参阅plunker它正在运作

你犯了这个错误:它应该是ng-include="'details.html'"而不是ng-include="details.html"

<script>标记在ng-controller内无效。