Rah*_*har 11 angularjs angularjs-directive
这不应该是一件难事,但我无法弄清楚如何最好地做到这一点.
我有一个父指令,如下所示:
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
// ...
]
};
});
Run Code Online (Sandbox Code Playgroud)
和儿童指令:
.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'
};
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能轻松地访问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>
Run Code Online (Sandbox Code Playgroud)
我们的想法是默认显示一组字段.如果单击,它们将成为输入并可以编辑.
从这篇SO帖子中汲取灵感,我在这个问题上得到了一个有效的解决方案.
我不得不改变一下.我也选择了一个独立的范围,editableString
因为更容易将正确的值绑定到模板.否则,您将不得不使用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();
}
};
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以通过在子指令链接函数中传递属性来访问父控制器
link: function (scope, element, attrs, parentCtrl) {
parentCtrl.$scope.editing = true;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16433 次 |
最近记录: |