在我的angularjs html文件中,我正在使用服务读取文件数据并在指令中显示数据。它在显示树视图时工作正常。我为每个项目添加了一个ng-click“ShowDetailsFunc()”,并希望从变量($ scope.testdata)获取详细信息。问题是我从服务获得的数据无法通过ng-click功能访问,并显示为“未定义”。我知道$ scope.testdata需要一些时间才能获得价值,因为它来自$ http服务,但我也试图获得一次它完全加载。据我所知,一旦设置了$ scope变量,就可以在整个控制器功能中访问,并且可以在任何地方访问。
我想过使用$ watch但我认为它用于观看正常变量。如果我的理解不对或者我在某处犯了一些错误,请帮忙。
我的指示如下,
mainApp.directive('collection', function () {
return {
restrict: "E",
replace: true,
scope: {collection: '='},
template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
}
})
mainApp.directive('member', function ($compile) {
var NewChild = "<li><span ng-click=ShowDetailsFunc()>{{member.NodeName}}</span></li>";
var linkerfunc = function(scope, element, attrs) {
var collectionSt = '<collection collection="member.children"></collection>';
$compile(collectionSt)(scope, function(cloned, scope) {
element.append(cloned);
});
scope.ShowDetailsFunc = function() {
scope.ShowDetailsCtrlFunc(element,event);
}
}
return {
restrict: "E",
replace: true,
scope: {member: '=', ShowDetailsCtrlFunc : '&'},
template: NewChild,
controller: 'TreeController',
link: linkerfunc
}
})
我的控制器功能,
mainApp.controller('TreeController', function ($scope,$http,getTestDataService,$timeout) {
$scope.Intialfunc = function() {
$scope.testdata = []
var filename = 'D:\\myxmlfile.xml'
getTestDataService.gettestdata(filename).then(function success(response){
$(response.data.children).each(function(index,value){
$scope.testdata.push(value);
})
console.log($scope.testdata) // showing data here.
});
}
$scope.ShowDetailsCtrlFunc = function(element,event) {
console.log("in function ShowDetailsCtrlFunc"); // coming to this fucntion on click.
console.log($scope.testdata) // but this one is not showing . shows undefined.
.....................................
some other code using $scope.testdata
.....................................
event.stopImmediatePropagation();
};
});
答案 0 :(得分:0)
默认情况下,angular不会将this
指令绑定到控制器,为此,您应该在return语句指令中使用bindToController
属性。有关详细信息,请查看this