我有以下代码:
<html ng-app="calApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("calApp", []);
app.controller('calController', function calController(){});
app.directive('calendar',function(){
return {
restrict: "E",
scope:{
friend: '='
},
template:"<h1>{{friend}}</h1>",
controller: function($scope){
console.log($scope.friend);
console.log("hi");
}
}
});
</script>
</head>
<body ng-controller="calController">
<calendar friend="Bob"></calendar>
</body>
</html>
我期待将“Bob”(或代替它的任何内容)记录到控制台并在页面上以粗体显示。而是将undefined
记录到控制台,页面上不显示任何内容。
有人知道我哪里出错吗?
部分我觉得这很简单,但我似乎无法弄清楚那是什么。
答案 0 :(得分:1)
因为你需要改变这个
friend: '='
到这个
friend: '@'
&#39; =&#39;用于变量(双向数据绑定)和&#39; @&#39;对于字符串
还有这个
friend: '='
你可以这样做
<calendar friend="'Bob'"></calendar>
答案 1 :(得分:0)
请运行以下代码段,检查console.log。
var app = angular.module("calApp", []);
app.controller('calController', function calController(){});
app.directive('calendar',function(){
return {
restrict: "E",
scope:{
friend: '@'
},
template:"<h1>{{friend}}</h1>",
controller: function($scope){
console.log($scope.friend);
console.log("hi");
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<body ng-controller="calController" ng-app="calApp">
<calendar friend="Bob"></calendar>
</body>
&#13;
答案 2 :(得分:0)
尝试:
scope:{
friend: '@'
},
绑定变量时使用 =