Page 70 - AngularJS权威教程
P. 70
50 第 8 章 指令简介
<div ng-controller="ParentController">
<p>We can access: {{ rootProperty }}
and {{ parentProperty }}</p>
<div ng-controller="ChildController">
<p>
We can access:
{{ rootProperty }} and
{{ parentProperty }} and
{{ childProperty }}
</p>
<p>{{ fullSentenceFromChild }}</p>
</div>
</div>
angular.module('myApp', [])
.run(function($rootScope) {
// 使用.run访问$rootScope
$rootScope.rootProperty = 'root scope';
})
.controller('ParentController', function($scope) {
// 使用.controller访问`ng-controller`内部的属性
// 在DOM忽略的$scope中,根据当前控制器进行推断
$scope.parentProperty = 'parent scope';
})
.controller('ChildController', function($scope) {
$scope.childProperty = 'child scope';
// 同在DOM中一样,我们可以通过当前$scope直接访问原型中的任意属性
$scope.fullSentenceFromChild = 'Same $scope: We can access: ' +
$scope.rootProperty + ' and ' +
$scope.parentProperty + ' and ' +
$scope.childProperty
});
在线示例:http://jsbin.com/URuyoG/1/edit,为方便学习,有些部分使用了彩色。
更多关于ng-controller的内容请查看9.2节。
注意,还有其他内置指令(比如ng-include和ng-view)也会创建新的子作用域,这意味着
它们在被调用时行为和ng-controller类似。我们在构造自定义指令时也可以创建新的子作用域。
8.2 向指令中传递数据
回顾一下如何定义指令:
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
template: '<a href="http://google.com">Click me to go to Google</a>'
}
});
注意,我们在模板中硬编码了URL和链接文本:
template:'<a href="http://google.com"> Click me to go to Google</a>'
AngularJS并没有限制在指令的模板中硬编码字符串。