0

I have the following service

function PathFactory() {
    this.path = null;
    this.setPath = function(path) {
        this.path = path;
    }
    return this;
}

My navigation controller:

function NavController($scope, PathFactory) {

    list = document.getElementsByTagName("ul");
    list = list[0];

    var items = list.getElementsByTagName("li");
    for(var i = 0 ; i < items.length ; i++) {
        items[i].setAttribute("navIndex", i);
        items[i].addEventListener("click", navClick);
    }

    function navClick(e) {
        switch(e.path[1].hash) {
            case "#home":
                PathFactory.setPath("home");
                break;
            case "#bots":
                PathFactory.setPath("bots");
                break;
            case "#servers":
                PathFactory.setPath("servers");
                break;
            case "#status":
                PathFactory.setPath("status");
                break;
        }
    }
}

And my content controller:

function ContentController($scope, PathFactory) {

    $scope.$watch(function() {
        return PathFactory.path;
    }, function (newValue) {
        alert("changed value");
    });

}

The $scope.$watch isn't running the function should the value of PathFactory.path be changed by the navigation controller, any way I can get this setup working?

Cheers guys.

3
  • After changing in NavController, ContentController will be call or not? Commented Aug 19, 2015 at 12:33
  • you checked for $emit and $on? Commented Aug 19, 2015 at 12:36
  • It's working now see Nano's answer - thanks anyway. Commented Aug 19, 2015 at 12:37

1 Answer 1

2

If you want that AngularJS calls the $watch() Method, then you have to call the $apply() Method manualy.

Angulars two-way-databinding only works, because everything that changes anything in $scope also calls the $apply Method. That way Angular knows something has changed.

Try to put this line of code $scope.$apply(); at the end of your navClick Function.

But you should definitely use a directive for event listeners and/or DOM-Manipulation

Sign up to request clarification or add additional context in comments.

2 Comments

By the way, the function navClick could be more dynamic if you change the switch to this: PathFactory.setPath(e.path[1].hash.substr(1));
Something tells me this is a very awful way of solving this problem.

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.