[英]Angular directive controller scope visibility
Question 题
Why isn't monkey
and selected
visible to the template? 为什么
monkey
和selected
对模板不可见?
Plunk 普拉克
http://plnkr.co/edit/djS0KWyfJNKD0tfZ0IiV?p=preview http://plnkr.co/edit/djS0KWyfJNKD0tfZ0IiV?p=preview
Code 码
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script type="text/javascript">
angular
.module('toruSelect', [])
.directive('toruSelect', function () {
return {
restrict: 'AE', // Allow usage as A - attribute, E - element
scope: { // Isolated scope
selected: '=' // Bi-directional binding to selected attribute,
},
controller: ['$scope', function ($scope) {
$scope.monkey = 'MONKEY';
console.log('toruSelect.controller.$scope', $scope);
}]
}
});
var app = angular.module('app', ['toruSelect']);
app.controller('AppCtrl', function($scope) {
$scope.val = 'initial';
$scope.appData = 'App data';
});
</script>
</head>
<body ng-controller="AppCtrl">
<h1>Directives and scopes..</h1>
<div toru-select selected="val">
<div style="color: red">RESULT: toruSelect.controller.monkey: {{monkey}}</div>
<div>EXPECTED: toruSelect.controller.monkey: MONKEY</div>
<div style="color: red">RESULT: toruSelect.controller.selected: {{selected}}</div>
<div>EXPECTED: toruSelect.controller.selected: initial</div>
</div>
</body>
Result 结果
Directives and scopes..
RESULT: toruSelect.controller.monkey:
EXPECTED: toruSelect.controller.monkey: MONKEY
RESULT: toruSelect.controller.selected:
EXPECTED: toruSelect.controller.selected: initial
As you pointed it out on the comment of your directive, it has an isolated scope, so that value attached with monkey
key is available on directive scope, not on controller one. 正如您在指令注释中指出的那样,它具有隔离的作用域,因此,
monkey
键附加的值可用于指令作用域,而不是控制器一。
For selected
, you have to display {{val}}
and not {{selected}}
as it's the variable concerned by the bi-directional binding on the directive scope. 对于
selected
,您必须显示{{val}}
而不是{{selected}}
因为它是指令范围上双向绑定所关注的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.