Angularjs指令内部指令

时间:2013-09-12 10:50:52

标签: angularjs

我有两个指令resourceformajax。他们在这里:

资源

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

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/。我$watchscope.action resource,它最终可用,但我想它后来绑定formajax与期望值之间的关系太迟了。 也许templateUrl和异步加载会导致问题,使某些绑定不可能或未处理?

2 个答案:

答案 0 :(得分:0)

我认为您可以尝试将父指令的控制器传递给子节点,这些值将在两个指令中同时绑定。我在这里做了一个例子: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 然后,在child指令中,formajax,您将需要父指令控制器,并在链接函数中传递它:

....
    require:'^parent',
    link:function(scope, elt, attr, parentCtrl){
        scope.$watch(function(){
            scope.childaction=parentCtrl.getAction()
        });

编辑:您仍然需要观看更改 现在,您可以从子项

中的父指令访问所有值

我希望这会对你有所帮助,

玩得开心

答案 1 :(得分:0)

我生气了,做了类似的事情:

    ($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

Hacky,但有效;)