访问控制器内的AngularJs指令scope.variable

时间:2018-01-19 07:18:36

标签: angularjs controller directive

return function (scope, iElement, iAttrs) {
    iElement.autocomplete({
        source:function(request, response) {
            var mastersList = new Array();
            var newRequest = request.term.substring(0, 3);
            if (request.term.length > 2 && scope.prerequest != newRequest) {
                scope.prerequest = newRequest;
                var url = "";
                if (scope.isCandidate == true) {
                    url = 'masters/getDataFromLookup/lkupid/' + scope.field.master_table_id + '/ac_param/' + newRequest + '/loginType/C';
                } else {
                    url = 'masters/getDataFromLookup/lkupid/' + scope.field.master_table_id + '/ac_param/' + newRequest;
                }
                HttpMethod.CallHttpMethod("GET", "", url).success(function(Resdata) {
                    var data = Resdata.data[0];
                    var masters = new Array();
                    for (var i = 0; i < data.length; i++) {
                        var master = new Object();
                        var model = data;
                        master.name = model[i].name;

                        master.id = model[i].id;
                        mastersList.push(master);
                        masters.push(master);
                    }
                }
                response(mastersList);
                scope.masters = masters;
                )
            }
        },
        select: function(event, ui) {
            $timeout(function() {
                scope.$parent.field.field_value = ui.item.name;
                scope.$parent.field.field_masterid = ui.item.id;
            },0);
        },
    });
}

该指令用于自动完成功能。我必须访问控制器中scope.masters的值。每次我尝试访问时,都是未定义的。提前致谢。

1 个答案:

答案 0 :(得分:0)

您必须确保该指令将其范围设置为false,因此它不使用隔离范围。此外,您还必须检查指令与控制器位于同一范围内。您可以使用像ng-inspect这样的镀铬扩展来轻松检查这一点,您可以在其中检查角度范围。

除此之外,最好使用隔离范围并将变量绑定到该范围,有点像:

scope: {
    masters: '=masters'
}

然后在你的HTML中

<input your-directive masters="masters" />

了解更多信息:https://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/