问题描述
我有一个包含菜单栏的所有页面的通用模板,它位于 ng-view
之外.从我的一个页面中,它位于 ng-view
内> 我想将输入数据绑定到这个模板区域(这个区域与输入页面在不同的控制器下).我的意思是当我输入名字时,名字会出现在模板区域.这可能吗?这是>
$rootScope
存在,但可用于作恶
AngularJS 中的作用域形成一个层次结构,原型是从树顶部的根作用域继承的.通常这可以忽略,因为大多数视图都有自己的控制器,因此也有自己的作用域.
有时您希望将一些数据全局化到整个应用程序中.对于这些,您可以像任何其他范围一样注入 $rootScope
并在其上设置值.由于作用域继承自根作用域,因此这些值将可用于附加到诸如 ng-show
之类的指令的表达式,就像本地 $scope
上的值一样.
当然,全局状态很糟糕,您应该谨慎使用 $rootScope
,就像您(希望)在任何语言中与全局变量一起使用一样.特别是,不要将它用于代码,仅用于数据.如果您想将一个函数放在 $rootScope
上,那么最好将它放在一个可以注入到需要的地方并且更容易测试的服务中.
相反,不要创建服务的唯一目的是存储和返回数据位.
—AngularJS常见问题 - $rootScope
存在,但可用于作恶
I have a general template for all pages which contains a menu bar and it is outside the ng-view
.From one of my page which is inside the ng-view
i want to bind input data to this template area(this area is under a different controller than the input page).I mean when i will enter name,the name will appear to the template area.Is it possible ?Here is the plunker
<body ng-app="sampleApp">
<div class="container">
<div class="row">
name is :{{name}}<br/>
username is :{{uname}}
<div class="col-md-3">
<ul class="nav">
<li><a href="#name"> Add name </a></li>
<li><a href="#uname"> add username </a></li>
</ul>
</div>
<div class="col-md-9">
<div ng-view></div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="app.js"></script>
</body>
The DEMO on PLNKR
$scope.obj
is working like a $rootScope
variable. Is it for prototypal inheritance?
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Each AngularJS application has exactly one root scope, but may have any number of child scopes.
ng-app --> $rootScope |- ng-controller --> $scope (container) |- ng-view --> $scope (view)
By using: <input ng-model="obj.name" />
the ng-model
directive in the view controller uses prototypical inheritance to find $scope.obj
from outside the view. It can then get and set the name
property of that object.
For more information, see AngularJS Developer Guide - Scope Hierarchies
这篇关于在 ng-view 之外绑定 Angularjs 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!