AngularJS : isolated scope + two-way binding + ng-

2019-07-21 23:01发布

问题:

the ng-repeat outputs nothing. in the link function, i can see $scope.clients is an array. if i remove the isolate scope, and use the parent scope, the ng-repeat works.

html with directive "clients".

<div container 
     ng-cloak 
     ng-app="summaryReportApp" 
     ng-controller="summaryReportController as summaryReport">

<fieldset clients="summaryReport.clients">
<legend>Clients</legend>
<div align="left">
    <div ng-repeat="client in clients track by $index">
        {{client}}
    </div>
</div>
</fieldset>

</div>

directive

var clients = function(){
    var definition = {
        restrict:       "A",
        scope:          {
                            clients:"=clients"
                        },
        link:           function($scope,$element,attributes){
                        }
    }

    return definition;
}

回答1:

This is a common question I seem to answer frequently. Directives can have other HTML Elements nested in them, in the same way that an <input> can be nested inside a <div>. However, the Elements nested inside the Directive are not part of the directive, and are not scoped to the directive, they are scoped to the HTML they are in. The only items that have access to the Isolated Scope are the compile, link, controller, and template items in the directive definition. If you moved your inner html from inside the fieldset into a template, it would function as expected.

You can also reference http://angular-tips.com/blog/2014/03/transclusion-and-scopes/ for more examples and ways to test this.