簡體   English   中英

Angular Js如何在指令中訪問$ scope

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

我為表單控件創建了指令[input,select and radio],每個輸入都有默認值,如果$ scope.answers有這個輸入值,那么這個值應該顯示在輸入框中。

下面的代碼無法通過鏈接功能進行工作

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

指令功能

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

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

您沒有訪問$scope的指令直接但你有一個link功能,您可以訪問scope到相應的指令。 但是,您無法像當前一樣設置值.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!!!');
    }
  }

其中element是包裝器元素div ,您必須.find('input') 1放置在其中的文本輸入。

1.如果jqLite之前不包括jQuery庫,則angular將使用jqLite ,並且.find()方法僅限於查找tagNames

普倫克


剛剛看到,您的范圍沒有answers屬性。 所以,那是行不通的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM