I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displays correctly when set independently.
Below is my code snippet:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body>
<div ng-app="mainApp">
<div ng-controller="MyController">
<div id="Details" class="Details">{{Details}}</div></br>
<div id="Test" class="Test">
<collection collection='testdata'></collection>
</div>
</div>
</div>
</body>
<script>
var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
return {
restrict: "E",
replace: true,
scope: {collection: '=', showFn : '&'},
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.TagName}}</span></li>";
return {
restrict: "E",
replace: true,
scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
template: NewChild,
controller: 'MyController',
link: function (scope, element, attrs) {
var collectionSt = '<collection collection="member.children"></collection>';
if (angular.isArray(scope.member.children)) {
$compile(collectionSt)(scope, function(cloned, scope) {
element.attr('xml-path', scope.member.TagPath);
element.append(cloned);
});
scope.ShowDetailsFunc = function() {
scope.ShowDetailsCtrlFunc(element,event);
}
}
}
}
})
mainApp.controller('MyController', function ($scope) {
$scope.testdata = [{"TagName":"MyRootNode","TagPath":">MyRootNode","children":[{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>...
$scope.Details = "defalut value"
$scope.ShowDetailsCtrlFunc = function(element,event) {
console.log("in function ShowDetailsCtrlFunc");
var myxmlpath = $(element).attr("xml-path")
$scope.Details = getObjects($scope.testdata, 'TagPath', myxmlpath)[0].TagName;
console.log($scope.Details)
//event.stopImmediatePropagation();
};
});
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
</script>
</html>
I would really appreciate any guidance on where I might be going wrong and how I can correct this issue. Thank you so much in advance for your help!