AngularJS – 从子目录访问父指令属性
发布时间:2020-12-17 09:03:18 所属栏目:安全 来源:网络整理
导读:这不应该是太难的事情,但我不知道如何最好地做到这一点. 我有一个父指令,就像这样: directive('editableFieldset',function () { return { restrict: 'E',scope: { model: '=' },replace: true,transclude: true,template: ' div class="editable-fieldset"
|
这不应该是太难的事情,但我不知道如何最好地做到这一点.
我有一个父指令,就像这样: 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',template: function (element,attrs) {
'<div>
<label>' + attrs.label + '</label>
<p>{{ model.' + attrs.field + ' }}</p>
...
</div>'
},require: '^editableFieldset'
};
});
如何从子指令中轻松访问模型并编辑父指令的属性?在我的链接函数中,我可以访问父范围 – 应该使用$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上有一个孤立的范围,因为它更容易绑定到模板的正确的值.否则,您将不得不使用编译或其他方法(如$transclude服务). 结果如下: JS: var myApp = angular.module('myApp',[]);
myApp.controller('Ctrl',function($scope) {
$scope.myModel = { property1: 'hello1',property2: 'hello2' }
});
myApp.directive('editableFieldset',template: '<div class="editable-fieldset" ng-click="edit()"><div ng-transclude></div></div>',link: function(scope,element) {
scope.edit = function() {
scope.editing = true;
}
},function($scope) {
this.getModel = function() {
return $scope.model;
}
}]
};
});
myApp.directive('editableString',scope: {
label: '@',field: '@'
},template: '<div><label>{{ label }}</label><p>{{ model[field] }}</p></div>',require: '^editableFieldset',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>
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
