我正在学习 AngularJS。我在将参数传递给指令时遇到问题。
如果模板具有 myJson
变量名称而不是 {{jsonVar}}
,则它可以正确显示表格。但是,当我尝试通过参数 {{jsonVar}}
将 json 对象名称传递给指令时,它不会加载模板本身。任何人都可以帮助我为什么它不起作用。
在 Controller 中,sample.json 被加载到 myJson
变量中
请让我知道我犯了什么错误。代码示例如下所示:Plunkr URL 也发布以供引用。
提前致谢
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'World';
$scope.myJson = null;
$http.get('sample.json').success(function(data) {
$scope.myJson = data;
console.log($scope.myJson);
});
}).directive("myTable", function() {
return {
restrict: 'E',
scope: {
jsonVar: '@'
},
template: "<table>" +
"<thead >" +
" <tr><td ng-repeat='(key,val) in {{jsonVar}}'>{{key}}</td></tr>" +
"</thead>" +
"<tbody>" +
"<tr ng-repeat='obj in {{jsonVar}}'>" +
"<td ng-repeat='(key,val) in obj'>{{val}} </td>" +
"</tr>" +
"</tbody>" +
"</table>"
};
});
我将参数传递给指令,如下所示:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<my-table jsonVar="myJson"></my-table>
最佳答案
您想要的是对 jsonVar 的引用。您应该将指令的范围定义更改为。
scope: {
jsonVar: '=' // 2 way binding by reference
}
驼峰式属性也会在 html 中以破折号进行转换。
<my-table json-var="myJson"></my-table>
我强烈建议阅读找到的指令的文档 here不管有多长。
关于javascript - 无法将参数传递给 angularjs 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484581/