【发布时间】:2013-12-05 17:19:28
【问题描述】:
我有一个自定义指令,它的目的是呈现一个小部件并将其绑定到一个变量。 每个变量都有不同的数据类型,因此会根据数据类型呈现不同的小部件。
我的问题是我可以传递变量的数据,但我无法将小部件绑定到它。
为了简化问题,我的小部件只是一个简单的文本输入。 当我尝试 $compile 小部件时,Angular 使用变量的值而不是绑定到它。
HTML:
<body ng-app="app" ng-controller="myCtrl">
<input type="text" ng-model="resource.name"></div>
<div custom-widget widget-type="widget" bind-to="resource"></div>
</body>
Javascript:
angular.module('app', [])
.directive('customWidget', function($compile) {
return {
replace: true,
template: '<div></div>',
controller: function($scope) {
},
scope: {
bindTo: "=bindTo",
widgetType: "=widgetType"
},
link: function(scope, iElem, iAttrs) {
var html = '<div>' + scope.widgetType.label + ':<input ng-bind="' + scope.bindTo[scope.widgetType.id] + '" /></div>';
iElem.replaceWith($compile(html)(scope));
}
};
})
.controller('myCtrl', function($scope) {
$scope.widget = {
id: 'name',
label: 'Text input',
type: 'text'
};
$scope.resource = {
name: 'John'
};
});
Plunker 演示:http://plnkr.co/edit/qhUdNhjSN7NlP4xRVcEA?p=preview
我还是 AngularJS 的新手,我的方法可能不是最好的,所以当然欢迎任何不同的想法!
【问题讨论】:
-
你想实现什么不清楚
-
在 Plunker 演示中,我希望将 2 个字段双向绑定到 $scope.resource.name