如何获得访问孤立范围指令ATTRS? [英] How to get access to a directive attrs with isolated scope?

查看:100
本文介绍了如何获得访问孤立范围指令ATTRS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获得通过的指令,并在同一时间,我需要得到ATTRS在指令中创建的模型。

I need to have access to model created by directive and in the same time I need to get attrs in the directive.

JS:

module.directive('createControl', function($compile, $timeout){
 return {            
   scope: {        
     name: '=Name' // Dynamically created ng-model in the directive element
   },
   link: function(scope, element, attrs){
     attrs.$observe('createControl', function(){
       attrs.createControl //is empty if scope is an object, otherwise it is passed from html attribute
     }
   }

HTML

<div class="control-group" ng-repeat="x in selectedControls">
  <div create-control="{{ x }}"></div>
</div>

如果范围被定义为一个对象, ATTRS 是空的,否则就值从HTML传递。

If scope is defined as an object, attrs is empty, otherwise it is value passed from html.

此行为的原因是什么?如何获得一个传递ATTRS和一个模型的访问?

What the cause of this behavior? How to get access to a passed attrs and to a models?

推荐答案

问题: 创建控需要评估 {{X}} 父范围之内,但通过使范围时,该指令被宣布创建一个分离范围的对象。这意味着 attrs.createControl 没有获得 X 。因此,它是空的。

The problem: create-control needs to evaluate {{x}} within the parent scope, but by making the scope an object when the directive is declared you create an isolate scope. This means that attrs.createControl doesn't have access to x. Therefore, it is empty.

一个解决方法::您可以解决这个问题几个方面,其中最好的是你的指令配置为接受 scope.createControl 成其分离通过一个属性范围。

One solution: You can fix this several ways, the best of which is to configure your directive to accept scope.createControl into its isolate scope through an attribute.

工作小提琴: http://jsfiddle.net/pvtpenguin/tABt6/

myApp.directive('createControl', function ($compile, $timeout) {
    return {
        scope: {
            name: '@', // Dynamically created ng-model in the directive element
            createControl: '@'
        },
        link: function (scope, element, attrs) {
            scope.$watch('createControl', function () {
                // the following two statements are equivalent
                console.log(attrs.createControl);
                console.log(scope.createControl);
            })
        }
    }
})

这篇关于如何获得访问孤立范围指令ATTRS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆