双向绑定指令范围的对象
Two-way bind an object of the scope of the directive
我正在尝试创建一个指令,该指令对传递的对象具有双向绑定:
angular.module('app').directive('lmDataBox', function () {
return {
restrict: 'A',
scope: {
lmdata: '=',
},
template: '<input type="text" ng-model="lmdata.displayValue">',
link: function link(scope, element, attrs) {
scope.lmdata.displayValue = 'testvalue';
}
};
但是,即使我将 "displayValue" 设置为字符串,输入框还是空的。
我做错了什么?
我可能已经发现你的问题了:
lmdata 可能未在您的父级范围内设置。这意味着当您尝试设置 scope.lmdata.displayValue 时,您尝试设置一个未定义的范围变量。
要解决这个问题,您必须像这样在父级范围内设置 lmdata:
$scope.lmdata = {'displayValue':''};
我在 plnkr 中创建了一个工作示例(为了方便,我只是将限制更改为 'E')here
我正在尝试创建一个指令,该指令对传递的对象具有双向绑定:
angular.module('app').directive('lmDataBox', function () {
return {
restrict: 'A',
scope: {
lmdata: '=',
},
template: '<input type="text" ng-model="lmdata.displayValue">',
link: function link(scope, element, attrs) {
scope.lmdata.displayValue = 'testvalue';
}
};
但是,即使我将 "displayValue" 设置为字符串,输入框还是空的。
我做错了什么?
我可能已经发现你的问题了:
lmdata 可能未在您的父级范围内设置。这意味着当您尝试设置 scope.lmdata.displayValue 时,您尝试设置一个未定义的范围变量。
要解决这个问题,您必须像这样在父级范围内设置 lmdata:
$scope.lmdata = {'displayValue':''};
我在 plnkr 中创建了一个工作示例(为了方便,我只是将限制更改为 'E')here