Kimchi Man
Kimchi Man

Reputation: 1171

Change scope values in the view

I'm learning AngularJS and I have a question.

Here is my code:

HTML (view):

...
<table>
    <tr ng-repeat="student in students">
        <td ng-class="{'student-highlight' : isStudent}">
            <input  type="checkbox"
                    ng-model="student.option"
                    ng-change="isStudent = checkStudent(student)" />
        </td>
 ...
<button type="button" ng-click="submit()">SUBMIT</button>

Controller:

$scope.checkStudent = function(student) {
    if(some_logic)
        return true; // It returns true for now
    else
        return false;
};

$scope.submit = function() {
    // I want to change isStudent in the view to false
};

So when a user change input box, it returns true so the cell is highlighted by the CSS class 'student-highlight'. I want to change the value 'isStudent' in the view after the user hit the button 'submit'.

To do that, I used $$childHead in the controller:

for(var cs = $scope.$$childHead; cs; cs = cs.$$nextSibling) {
    if(cs.isStudent)
        cs.isStudent = false;
}

but I don't like what I did here - it's not pretty. I think I could use $scope.$emit() or $scope.$broadcast(), but I don't know how.

Please help me out!!

Upvotes: 1

Views: 272

Answers (2)

Owen
Owen

Reputation: 718

A way to do this is to have a bools = {} object in your controller. Then, your view and your controller can simply access bools.isStudent for the current value. This gets even better when you migrate to the preferred Controller As syntax.

As an aside, you should never use any $$ property as they are private. From the documentation:

$ Prefix Naming Convention

You can create your own services, and in fact we will do exactly that in step 11. As a naming convention, Angular's built-in services, Scope methods and a few other Angular APIs have a $ prefix in front of the name.

The $ prefix is there to namespace Angular-provided services. To prevent collisions it's best to avoid naming your services and models anything that begins with a $.

If you inspect a Scope, you may also notice some properties that begin with $$. These properties are considered private, and should not be accessed or modified.

Upvotes: 1

Jaydee88
Jaydee88

Reputation: 66

Perhaps you might want to take a look at Angularjs form validation.
First you define the student-highlight under input.ng-dirty.
Then to clear the student-highlight, you can call $scope.form.$setPristine() in submit() to reset the form.

Upvotes: 1

Related Questions