Different ng-include's on the same page: how to send different variables to each?

前端 未结 15 1383
北海茫月
北海茫月 2020-12-04 12:17

I\'ve got a page in my AngularJS app in which I would like to include the same html partial, but with different variables. If I do this in my main html:

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 13:04

    Using onload is not a clean solution because it litters the global scope. If you have something more complex, it'll start to fail.

    Using a new directive instead of ng-include is a cleaner solution.

    The ideal usage looks like:

    The directive is:

    .directive(
      'ngIncludeTemplate'
      () ->
        {
          templateUrl: (elem, attrs) -> attrs.ngIncludeTemplate
          restrict: 'A'
          scope: {
            'ngIncludeVariables': '&'
          }
          link: (scope, elem, attrs) ->
            vars = scope.ngIncludeVariables()
            for key, value of vars
              scope[key] = value
        }
    )
    

    You can see that the directive doesn't use the global scope. Instead, it reads the object from ng-include-variables and add those members to its own local scope.

    ng-include is not that reusable because it has access to the global scope. It's a little weird.

    I hope this is what you would like; it's clean and generic.

提交回复
热议问题