CrazySynthax CrazySynthax - 28 days ago 8
AngularJS Question

AngularJS: How to initialize a $scope attribute

I wrote the following small angular code snippet:

html file:

<body ng-controller="myCtrl">
<div class="container">
....
</div>
</body>


javascript file:

app.controller('myCtrl', function($scope) {
$scope.white_sld = get_init_white_sld();
$scope.get_soldier_style = function is_soldier(loc) {

var sld_color = get_soldier_color(loc);
if (sld_color == "") {
return ""; // no soldier in this square
} else {
return {
'width': '80%', 'height': '80%', 'border-radius': '80%', 'background-color': sld_color,
'margin': 'auto auto', 'vertical-align': 'middle'
}
}

function get_soldier_color(loc) {
for (var i = 0; i < white_sld.length; i++) {
if ((loc[0] == white_sld[i][0]) && (loc[1] == white_sld[i][1])) {
return "white"
}
}
for (var i = 0; i < black_sld.length; i++) {
if ((loc[0] == black_sld[i][0]) && (loc[1] == black_sld[i][1])) {
return "black"
}
}
return ""; // no soldier found
}
}
});

function get_init_sld_line(x_loc, y_loc, color) {
var line_sld = [];
for (var i = 0; i < 4; i++) {
line_sld.push(new Soldier(x_loc + 2 * i, y_loc, color));
}
return line_sld;
}


function get_init_white_sld() {
var init_white_sld = [];
init_white_sld.push(get_init_sld_line(0, 0, "white"));
init_white_sld.push(get_init_sld_line(1, 1, "white"));
init_white_sld.push(get_init_sld_line(0, 2, "white"));
return init_white_sld;
};


My problem with this code is that after the line "$scope.white_sld = get_init_white_sld();", $scope.white_sld gets the return value of the function get_init_white_sld(). However, when it gets inside the function 'is_soldier', then $scope.white_sld becomes undefined. My question is why and how can I resolve it?

Answer

That's because you should use $scope.white_sld within that function, not just white_sld.