Angular: 在编译期间将数据传递给指令

Angular: passing data to directive during compile

尝试做这样的事情:

var data = {some: 'data'}

var subcomponent = $compile('<div component-' + componentName + ' ng-model="'+data+'"></div>')($scope);

$element.find('.container').html( subcomponent[0] );

我收到错误:

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object]] starting at [Object]]

正在尝试将此数据添加到 link 范围。有什么方法可以将数据传递到指令范围吗?

ng-model 表达式必须是可以设置值的 属性。所以你需要做类似的事情。

$scope.data = {some: 'data'};// Set a property on the scope

/*Bind data to the ng-model*/
var subcomponent = $compile('<div component-' + componentName + ' ng-model="data"></div>')($scope);

在您的情况下,您正在尝试向字符串添加一个对象,这会将对象转换为其字符串表示形式,即 [object Object]。因此,您需要在作用域上设置一个 属性 名称 (existing/non-existing)。