我有我的输入指令,它从 html 中获取输入值,并更新角度模型:
.directive('input', function($parse) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
然后我有我的 html,其中绑定了 html 值和角度模型:
<div ng-controller="form" class="form">
<h2>Form with controller</h2>
<input type="text" ng-model="item.example" value="defaultValue">
<button ng-click="checkValue()">Check value</button>
</div>
当我作为控制器运行测试时,它可以完美运行:
.controller('form', function($scope) {
$scope.item = {};
$scope.checkValue = function() {
console.log('checkValue', $scope.item);
};
})
但作为嵌套指令,它没有得到值:
.directive('form', function() {
return {
restrict: 'C',
link: function(scope, element, attrs) {
scope.item = {};
scope.checkValue = function() {
console.log('checkValue', scope.item);
};
}
};
})
我的猜测是指令范围是分开的,所以一个指令不会影响另一个指令,但是它与控制器 + 指令一起工作正常吗?
我尝试使用此处的建议更改指令范围: 为什么我的 AngularJS 指令共享范围?
.directive('input', function($parse) {
return {
restrict: 'E',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs) {
if (attrs.ngModel && attrs.value) {
$parse(attrs.ngModel).assign(scope, attrs.value);
}
}
};
});
但是不能让这两个指令共享相同的范围。这可能吗?
这是我的演示,展示了这两种方法: https ://jsfiddle.net/kmturley/L1bky0g0/1/