How to specify model to a ngInclude directive in AngularJS?

前端 未结 6 1715
北海茫月
北海茫月 2020-11-30 02:48

I would like to use the same HTML template in 3 places, just each time with a different model. I know I can access the variables from the template, but there names will be d

6条回答
  •  迷失自我
    2020-11-30 03:25

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

    There should be a way to set local variables. 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.

    It's clean and generic.

提交回复
热议问题