我有以下自定义指令customerDirective
:
var app = angular.module('directiveApp', []);
var dirController = app.controller('DirectiveController', function() {
this.customer = {
name: 'James',
address: 'Mellieha'
};
});
dirController.directive('customerDirective', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
我在index.html
中调用了它,如下所示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example12-production</title>
<script src="../../bower_components/angular/angular.min.js"></script>
<script src="directive.js"></script>
</head>
<body ng-app="directiveApp">
<div ng-controller="DirectiveController">
<div customer-directive></div>
</div>
</body>
</html>
然而输出的结果并不像预期的那样:
Name: Address:
出于某种原因,未捕获包含客户详细信息的角度表达式。我辞职的事实是,我可能忽略了一些非常明显的事情,但到目前为止我还没有进行过管理。
PS:此示例直接来自AngularJS开发人员指南,特别是来自this部分
答案 0 :(得分:2)
您有两种方法可以解决此问题:
$ scope的示例:
var app = angular.module('directiveApp', []);
app.controller('DirectiveController', function($scope) {
$scope.customer = {
name: 'James',
address: 'Mellieha'
};
});
app.directive('customerDirective', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});
控制器为(没有$ scope)的示例:
app.controller('DirectiveController', function() {
this.customer = {
name: 'James',
address: 'Mellieha'
};
});
app.directive('customerDirective', function() {
return {
template: 'Name: {{dirCtrl.customer.name}} Address: {{dirCtrl.customer.address}}'
};
});
<body ng-app="directiveApp">
<div ng-controller="DirectiveController as dirCtrl">
<div customer-directive></div>
</div>
</body>
答案 1 :(得分:0)
如果你改变这个 - &gt; $范围其工作
var app = angular.module('directiveApp', []);
var dirController = app.controller('DirectiveController', function($scope) {
// Here Change
$scope.customer = {
name: 'James',
address: 'Mellieha'
};
});
dirController.directive('customerDirective', function() {
return {
template: 'Name: {{customer.name}} Address: {{customer.address}}'
};
});