Search code examples
javascriptangularjsangularjs-ng-click

ng-click gives "href undefined " error on a function call with a parameter


After seeing multiple issues around this, I'm still unable to figure out why the error occurred.

Here is my code so far:

app.js

myApp.controller("myController", function($scope, $window) {
    $scope.redirectto = function (id) {
        if(id === 'test') {
            $window.location.href = "http://mydomain.test.com/";      
        }
    };
};

html file:

<div layout="column" flex=40 layout-align="center center"
     ng-click="redirectto('test')" role="button"><span>Test</span>
</div>

There is no much complication am looking here.But when I amusing grunt to build the source, I am getting the following error.

TypeError: Cannot set property 'href' of undefined


Solution

  • Use $location.path:

    $location.path('http://mydomain.test.com/');
    

    In your full code, it will be:

    myApp.controller("myController", function($scope, $location) {
        $scope.redirectto = function (id) {
            if(id === 'test') {
                $location.path('http://mydomain.test.com/');
            }
        };
    };