1

How is it that the first function works, yet the second one doesn't?

<p ng-style="colors.one">1</p>


$scope.turnOn = function()
    {
        $scope.colors.one = {color: "green"};
    }

$scope.turnOff = function(num)
    {
        $scope.colors.num = {color: "red"};
    }

$scope.turnOn();
$scope.turnOff(one);

EDIT I tried adding num on $scope.colors like you guys suggested, still can't seem to figure it out.

$scope.turnOn = function(num)
    {
        $scope.colors[num] = {color: "green"};
    }

$scope.turnOff = function(num)
    {
        $scope.colors[num] = {color: "red"};
    }

I'm calling the functions through

<button ng-switch-when='false' ng-click='turnOn(one)'>
<button ng-switch-when='true' ng-click='turnOff(one)'>
1
  • Have you tried $scope.colors[num] = {color: "red"}; ? Commented Sep 14, 2015 at 23:51

4 Answers 4

2

num is not defined on colors. You can access the property num like this.

$scope.colors[num] = {color: "red"};
Sign up to request clarification or add additional context in comments.

Comments

1

i.e because you want to pass string "one" and not the value of scope property one via ng-click function argument in order to access it as:

<p ng-style="colors.one">1</p>

i.e

<button ng-switch-when='false' ng-click='turnOn("one")'>
<button ng-switch-when='true' ng-click='turnOff("one")'>

When you do ng-click='turnOn(one)' it is equivalent to calling the function turnOn with the value of $scope.one which has no value in your case, and using the bracket notation will just assign the value to the object, i.e $scope.colors[num] = ...

Comments

0

The parameter 'num' has no association to $scope.colors.num

should be

$scope.colors[num] = {color: "red"};

Comments

0

you have to reference variable property names with different notation:

$scope.turnOff = function(num) {
    $scope.colors[num] = {color: "red"};
};

should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.