Angularjs父范围使用子范围'属性

时间:2015-12-19 14:21:28

标签: javascript angularjs

angular.module('myApp',[])
.controller('Parent',['$scope',function($scope){
    //define nothing  
}]).controller('Child',['$scope',function($scope){
    $scope.user={username:''};//define an object user
}])



<div ng-app="myApp">
    <div ng-controller="Parent">
        {{user}}<!--print nothing-->
        <div ng-controller="Child">
            {{user}} <!--print an object-->
        </div>
    </div>
</div>

如何在不使用注入$rootScope

的情况下处理上述问题

2 个答案:

答案 0 :(得分:0)

根据您的评论...

  

我希望父用户不使用$ rootScope

打印子用户的值

...您无法完成此操作,因为父作用域不能从子作用域继承,因为它是当前定义的。视图控制器根据其节点结构从其父控制器继承。

<parent-node>
    {{user.name}} 
    <hr/>
    <child-node> 
        <!-- user inherit from parent node's scope by default -->
        {{user.email}}
    </child-node>
    <another-child-node> 
        <!-- user inherit from parent node's scope by default -->
        {{user.someOtherData}}
    </another-child-node>

您需要在父范围内定义user,如下所示:

.controller('Parent',['$scope',function($scope){
    $scope.user = {};
}])
.controller('Child',['$scope',function($scope){
}])  

...或者您可以通过指令处理此问题,具体取决于最终用户体验。

答案 1 :(得分:0)

当人们使用$ scope而不阅读范围文档时,这是一个问题。 这就是为什么我总是告诉人们不要使用$ scope来绑定对象/函数。这个和可维护性。

<强>控制器:

angular.module('myApp',[])
    .controller('Parent',['$scope',function(){
        //define nothing
    }])
    .controller('Child',['$scope',function(){
        this.user = {username:''}; //define an object user
    }]);

<强> TEMPLATE:

<div ng-app="myApp">
    <div ng-controller="Parent as parentCtrl">
        {{ parentCtrl.user }} <!-- undefined -->
        <div ng-controller="Child as childCtrl">
            {{ childCtrl.user }} <!-- object -->
        </div>
    </div>
</div>