【发布时间】:2014-08-07 14:03:22
【问题描述】:
我无法确定如何定义一个自定义指令:
- 使用隔离范围,并且
- 在其模板的新范围内使用 ng-model 指令。
这是一个例子:
HTML:
<body ng-app="app">
<div ng-controller="ctrl">
<dir model="foo.bar"></dir>
Outside directive: {{foo.bar}}
</div>
</body>
JS:
var app = angular.module('app',[])
.controller('ctrl', function($scope){
$scope.foo = { bar: 'baz' };
})
.directive('dir', function(){
return {
restrict: 'E',
scope: {
model: '='
},
template: '<div ng-if="true"><input type="text" ng-model="model" /><br/></div>'
}
});
此处所需的行为是输入的值通过指令的(隔离)范围model 属性绑定到外部范围的foo.bar 属性。这不会发生,因为模板封闭 div 上的 ng-if 指令创建了一个新范围,因此更新的是该范围的 model,而不是指令的范围。
通常,您通过确保表达式中有一个点来解决这些 ng-model 问题,但我在这里看不到任何方法。我想知道我是否可以在我的指令中使用这样的东西:
{
restrict: 'E',
scope: {
model: {
value: '=model'
}
},
template: '<div ng-if="true"><input type="text" ng-model="model.value" /><br/></div>'
}
但这不起作用......
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope