我正在试图弄清楚为什么以下内容无法正常工作。我以为它会显示: 用户:Jakob Jenkov用户:John Doe
然而,它显示了这个:
用户:用户:
HTML:
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MyController as $ctrl">
<userinfo user="jakob"></userinfo>
<userinfo user="john"></userinfo>
</body>
</html>
JAVASCRIPT:
var myapp = angular.module('plunker', []);
myapp.directive('userinfo', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>";
directive.scope = {
user : "="
}
return directive;
});
myapp.controller("MyController", function() {
var $ctrl = this;
$ctrl.jakob = {};
$ctrl.jakob.firstName = "Jakob";
$ctrl.jakob.lastName = "Jenkov";
$ctrl.john = {};
$ctrl.john.firstName = "John";
$ctrl.john.lastName = "Doe";
});
答案 0 :(得分:1)
您正在使用Controller As语法,因此您需要将控制器别名$ctrl
添加到传递给指令的变量中:
<body ng-controller="MyController as $ctrl">
<userinfo user="$ctrl.jakob"></userinfo>
<userinfo user="$ctrl.john"></userinfo>
</body>
如果没有$ctrl
,angular将直接在$scope
上查找未设置的变量,因此将undefined
传递给您的指令而不是所需的用户对象。
答案 1 :(得分:0)
一种方法是这样的:
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script>
var myapp = angular.module('plunker', []);
myapp.directive('userinfo', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>";
directive.scope = {
user : "="
}
return directive;
});
myapp.controller("MyController", function() {
this.jakob = {
firstName: "Jakob",
lastName: "Jenkov"
}
this.john = {
firstName: "John",
lastName: "Doe"
}
});
</script>
</head>
<body ng-controller="MyController as myCtrl">
<userinfo user="myCtrl.jakob"></userinfo>
<userinfo user="myCtrl.john"></userinfo>
</body>
</html>