这应该不是一件太难的事情,但我不知道如何最好地做到这一点。
我有一个父指令,如下所示:
directive('editableFieldset', function () {
return {
restrict: 'E',
scope: {
model: '='
},
replace: true,
transclude: true,
template: '
<div class="editable-fieldset" ng-click="edit()">
<div ng-transclude></div>
...
</div>',
controller: ['$scope', function ($scope) {
$scope.edit = ->
$scope.editing = true
// ...
]
};
});
还有一个子指令:
.directive('editableString', function () {
return {
restrict: 'E',
replace: true,
template: function (element, attrs) {
'<div>
<label>' + attrs.label + '</label>
<p>{{ model.' + attrs.field + ' }}</p>
...
</div>'
},
require: '^editableFieldset'
};
});
如何从子指令轻松访问父指令的 model
和 editing
属性?在我的链接函数中,我可以访问父范围 - 我应该使用 $watch
来监视这些属性吗?
总而言之,我想要的是:
<editable-fieldset model="myModel">
<editable-string label="Some Property" field="property"></editable-string>
<editable-string label="Some Property" field="property"></editable-string>
</editable-fieldset>
这个想法是默认显示一组字段。如果单击,它们将成为输入并且可以编辑。
最佳答案
从 this SO post 获取灵感,我有一个可行的解决方案 here in this plunker .
我必须做出很大的改变。我还选择在 editableString
上设置一个独立的范围,因为将正确的值绑定(bind)到模板更容易。否则,您将不得不使用 compile
或其他方法(例如 $transclude
服务)。
结果如下:
JS:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl', function($scope) {
$scope.myModel = { property1: 'hello1', property2: 'hello2' }
});
myApp.directive('editableFieldset', function () {
return {
restrict: 'E',
scope: {
model: '='
},
transclude: true,
replace: true,
template: '<div class="editable-fieldset" ng-click="edit()"><div ng-transclude></div></div>',
link: function(scope, element) {
scope.edit = function() {
scope.editing = true;
}
},
controller: ['$scope', function($scope) {
this.getModel = function() {
return $scope.model;
}
}]
};
});
myApp.directive('editableString', function () {
return {
restrict: 'E',
replace: true,
scope: {
label: '@',
field: '@'
},
template: '<div><label>{{ label }}</label><p>{{ model[field] }}</p></div>',
require: '^editableFieldset',
link: function(scope, element, attrs, ctrl) {
scope.model = ctrl.getModel();
}
};
});
HTML:
<body ng-controller="Ctrl">
<h1>Hello Plunker!</h1>
<editable-fieldset model="myModel">
<editable-string label="Some Property1:" field="property1"></editable-string>
<editable-string label="Some Property2:" field="property2"></editable-string>
</editable-fieldset>
</body>
关于AngularJS - 从子指令访问父指令属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20212354/