Search code examples
javascriptangularjsangularjs-scope

Using $location.url() inside a directive not working in angularjs


I have a directive and inside it, I used the $location.url() but it seems not working, and I think I need to inject something on my app but I don't know where to inject it. By the way I'm new to angularJS. Here's my code:

app.controller('CVSRRC-CTRL', function($scope,$http,$location){

        // some codes here

});
app.directive('cvsrrc', [function(){
return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.bind('dblclick', function(){
            $location.url("admin");
        });
      }
    }
}]);

It doesn't work, but I tried to replace the $location.url("admin"); to alert(1) It works properly. And when I checked the console it says that $location is undefined. What should I do ?


Solution

  • You need to inject $location as a dependency and you need to call $apply so that angular will trigger a digest cycle:

    angular.module('myapp', ['ngRoute'])
      .config(['$routeProvider', function($routeProvider){
      $routeProvider
        .when("/", {
            template: '<div cvsrrc class="box">  </div>'       
        })
        .when("/admin", {
            template : "ADMIN"
        })
      }])
      .directive('cvsrrc',  ['$location', function($location){
        return {
           restrict: 'A',
            link: function(scope, element, attrs){
                element.bind('dblclick', function(){
                  scope.$apply(function(){
                    $location.path("/admin");
                  });
                });
              }
            }
      }]);
    .box{
      height:100px; 
      width:100px; 
      background:#ff0000;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.6.1/angular-route.min.js"></script>
    <div ng-app="myapp">
      <ng-view>
        
      </ng-view>
    </div>