directive 中的scope 的边界问题

directive transclude 外部的html 部分的作用域只能获取到外层的ng-controller的作用域,
例如 <box> 用户名: {{user}}</box> 只能获取到ng-controller的scope.user 无法获取到box的scope.user,

只有处于template定义的 template:"<div> {{ scope }}</div>" html 可以获取到 directive 的scope
不知道有没有什么方法能通过 transclude 将 dir的scope 传到HTML 上,因为看到ng-isolate-scope 理论上应该应该可是实现 isolate中的scope 绑定吧

阅读 2.6k
2 个回答

transclude是可以传入你自己的scope的,例如:

jsangular.module('xx', [])
.directive('box', function() {
    return {
        scope: {usr:'yy'},
        transclude: true,
        template: '<div>in directive:{{usr}}<p></p></div>',
        compile: function(ele, attr, transcludeFn) {
            return function(scope, ele, attr) {
                transcludeFn(scope, function(contents) {
                    ele.find('p').append(contents)
                })
            }
        }
    }
})
html<box><span>{{usr}}</span></box>

可以写成<box user='user'>
定义directive时候参数scope写{user:'='}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题