简体   繁体   English

Angular Js如何在指令中访问$ scope

[英]Angular Js how to access $scope in directive

I created directive for form controls[input, select and radio], Each input have default value, if $scope.answers have this input value then this value should show in input box. 我为表单控件创建了指令[input,select and radio],每个输入都有默认值,如果$ scope.answers有这个输入值,那么这个值应该显示在输入框中。

Below code is not working from link fucntion 下面的代码无法通过链接功能进行工作

if($scope.answers.PC && $scope.answers.PC != '')
                {
                    element.val = $scope.answers.PC;
                }

Directive function 指令功能

function textControlDir()
    {
        return {
            transclude: true,
            restrict: 'E',
            scope: {
                queObj: '=',
                },
            template: '<div class="form-group">\n\
<label for="{{queObj._attributeName}}" class="col-sm-5 control-label">{{queObj._text}}</label>\n\
<div class="col-sm-6"><input type="text" name="{{queObj._attributeName}}" class="form-control" id="{{queObj._attributeName}}" value="{{queObj._pageAttributes.defaultValue}}"></div>\n\
</div>'
            ,
            link: function ($scope,scope, element, attrs)
            {
                if($scope.answers.PC && $scope.answers.PC != '')
                {
                    element.val = $scope.answers.PC;
                }
                console.log($scope);
            }
        };
    }

HTML 的HTML

<text-control-dir data-que-obj="que.QuestionData"></text-control-dir>

You don't have access to the $scope in the directives directly but as you have a link function you can access the scope to the respective directive. 您没有访问$scope的指令直接但你有一个link功能,您可以访问scope到相应的指令。 Yet you can't set values like you are doing currently .val is a wrong way to set: 但是,您无法像当前一样设置值.val是错误的设置方式:

link: function(scope, element, attrs) {
    if (scope.answers && scope.answers !== undefined) {
      element.find('input').val(scope.answers.PC); // <---this is the way to set value
    }else{
      element.find('input').val('No vales found!!!');
    }
  }

Where element is the wrapper element div and you have to .find('input') 1 the text input placed inside it. 其中element是包装器元素div ,您必须.find('input') 1放置在其中的文本输入。

1. If jQuery library is not included before angular, angular will use jqLite and where .find() method is restricted to have a lookup of tagNames only. 1.如果jqLite之前不包括jQuery库,则angular将使用jqLite ,并且.find()方法仅限于查找tagNames

Plnkr 普伦克


Just saw, your scope doesn't have answers property. 刚刚看到,您的范围没有answers属性。 So, that won't work. 所以,那是行不通的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM