当在我的链接函数中使用$ scope传递值to directive时,我能够使用变量attrs访问它们,而如果我使用控制器作为语法传递值,我只能访问传递的字符串。这是我的代码
指令调用
<div linear-chart chart-data="salesData"></div></div>
<div linear-chart2 chart-data="ctrl.salesData2"></div></div>
指令代码
app.directive('linearChart', function($window){
return{
restrict:'EA',
template:"some template",
link: function(scope, elem, attrs){
console.log(attrs.chartData);
}
}
}
这里attrs.chartData显示在根控制器中传递的数据为$ scope.salesData为json
app.directive('linearChart2', function($window){
return{
restrict:'EA',
template:"some template",
link: function(scope, elem, attrs){
console.log(attrs.chartData);
}
}
}
此处chartData仅显示字符串ctrl.salesData2。我如何提前感谢。
答案 0 :(得分:1)
要获取对象,应评估attrs.chartData(通过范围。$ eval)
<div linear-chart chart-data="salesData"></div>
console.log(scope.$eval(attrs.chartData))
或者如果你想获得json字符串,请使用{{}}
<div linear-chart chart-data="{{ salesData }}"></div>
无论控制器的语法是什么。
答案 1 :(得分:1)
使用指令的对象绑定:
app.directive('linearChart2', function($window){
return{
restrict:'EA',
scope: {
chartData: "="
},
template:"some template",
link: function(scope, elem, attrs){
console.log(scope.chartData);
}
}
}
或者,您只需使用$scope.$eval
评估给定的表达式:
app.directive('linearChart2', function($window){
return{
restrict:'EA',
template:"some template",
link: function(scope, elem, attrs){
var evaluatedData = scope.$eval(attrs.chartData);
console.log(evaluatedData);
}
}
}
答案 2 :(得分:0)
您应该使用双括号{{ }}
来显示模型中的内容:
(function(angular) {
'use strict';
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
var vm = this;
vm.type = "Name";
vm.type1 = "Address";
}])
.directive('myCustomer', function() {
return {
template: function(elem, attr) {
return attr.type;
}
};
});
})(window.angular);
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
&#13;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-directive-template-url-fn-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller as ctrl">
<div my-customer type="{{ctrl.type}}"></div>
<div my-customer type="{{ctrl.type1}}"></div>
</div>
</body>
</html>
<!--
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
&#13;
我希望它能解决你的问题