我知道如果我有一个HTML指令,我可以将$ scope中的对象传递给它:
<mydirective some-data="someData"></mydirective>
...其中someData
可能是JSON对象。
如果我动态创建指令并使用someData
,是否可以将引用传递给$compile
?
$scope.someData = { firstName: 'John', lastName: 'Doe' };
var link = $compile("<mydirective some-data='???'></mydirective>");
var content = link($scope);
$(body).append(content);
答案 0 :(得分:-2)
是的,您可以将对象传递给
var myApp = angular.module('myApp',[]);
myApp.directive('passObject', function() {
return {
restrict: 'E',
scope: { obj: '=' },
template: '<div>Hello, {{obj.prop}}!</div>'
};
});
myApp.controller('MyCtrl', function ($scope) {
$scope.obj = { prop: "world" };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<div ng-controller="MyCtrl">
<pass-object obj="obj"></pass-object>
</div>
&#13;
var myApp = angular.module('myApp',[]);
myApp.directive('passObject', function() {
return {
restrict: 'E',
scope: { obj: '=' },
template: '<div>Hello, {{obj.prop}}!</div>'
};
});
myApp.controller('MyCtrl', function ($scope) {
$scope.obj = { prop: "world" };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<div ng-controller="MyCtrl">
<pass-object obj="obj"></pass-object>
</div>
&#13;
指令