我有两个指令,resource
和formajax
。下面是它们:
资源
resource.coffee (部分)
(...)
($http, $location, $compile) ->
restrict: "E"
templateUrl: templateUrl
scope:
action: "@"
transclude: true
link: (scope, element, attributes) ->
(...)
resource.html
<div class="resource">
<style type="text/css">
.resource .new-record {
padding: 10px;
}
</style>
<button class="button" ng-click="addRecord()">+ Dodaj wiadomość</button>
<div class="new-record" ng-show="showAddForm">
<formajax action="{{action}}" />
</div>
<div ng-transclude></div>
</div>
和金刚
formajax.coffee (部分)
(...)
($http, $location) ->
restrict: "E"
scope:
action: "@"
title: "@"
formStatus: "="
additionalFields: "="
onData: "&"
templateUrl: templateUrl
link: (scope, element, attributes) ->
(...)
formajax.html
<form method="post" action="{{action}}" role="form" class="form-ajax">
<fieldset>
<legend>{{title}}</legend>
<div ng-bind-html-unsafe="form"></div>
<button type="button" ng-click="submit()" class="btn button">Wyślij</button>
</fieldset>
</form>
自举
我就是这样开始一切的:
<resource action="/api/messages/">
问题是,action
不是在链接时传递给formajax
的,而是undefined
而不是/api/messages/
。它是I $watch
scope.action
is resource
,它最终是可用的,但我认为它后来被绑定了,太晚了,无法将formajax
与所需的值连接起来。也许templateUrl
和异步加载会引发问题,使某些绑定不可能或无法处理?
发布于 2013-09-12 12:36:09
我认为您可以尝试将父指令的控制器传递给子指令,同时在两个指令中绑定值。我在这里做了一个例子:http://jsfiddle.net/DotDotDot/pVYL6/3/ (我不能使用您的代码,所以我使用了更短的代码)
实际上,我在第一个指令(您的resource
指令)中添加了一个控制器,其中我定义了一些getter:
.directive('parent',function(){
return {
scope:{action:'@'},
controller: function($scope, $element, $attrs) {
this.getAction=function(){
return $scope.action;
}
}
}
});
指令获取参数中的操作,getAction()
可以访问该操作。我使用this
而不是$scope
,因为目标是在另一个指令中使用控制器。您仍然可以添加resource
指令的所有代码,只需在控制器中添加一个getter即可。
然后,在子指令formajax
中,您将需要父指令控制器,并将其传递到链接函数中:
....
require:'^parent',
link:function(scope, elt, attr, parentCtrl){
scope.$watch(function(){
scope.childaction=parentCtrl.getAction()
});
编辑:您仍然需要$watch更改
现在,您可以从子指令中的父指令访问所有值。
我希望这能帮到你
玩得开心
发布于 2013-09-12 15:03:46
我生气了,做了这样的事:
($http, $location, $compile) ->
restrict: "E"
templateUrl: templateUrl
scope:
action: "@"
transclude: true
link:
pre: (scope, element, attributes) ->
scope.action = attributes.action
post: (scope, element, attributes) ->
scope.form = $compile("""<formajax action="#{scope.action}" />""") scope
scope.showAddForm = false
scope.addRecord = ->
scope.showAddForm = true
(无趣,但有效;)
https://stackoverflow.com/questions/18762214
复制相似问题