[英]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.