模拟“<a href="">&#34; in Angular

时间:2016-05-30 18:39:26

标签: javascript html angularjs

I have a situation (modal popup) that classical link using <a href> does not work, so I need to simulate that link behavior in a <div>. CODEPEN link

var myApp = angular.module('myApp', []);

myApp.controller('testCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.greeting = 'Hola!';
  $scope.myAlert = function(event) {
    console.log('this is the $scope.greeting');
    console.log($scope.greeting);
    console.log('this is the $window.location.href:');
    console.log($window.location.href);
    console.log('this is the event.target.dataset.href:');
    console.log(event.target.dataset.href);   
    $window.location.href = event.target.dataset.href;
  }
}]);
<div ng-app="myApp" ng-controller="testCtrl">
  <div data-href="http://test.com" ng-click="myAlert($event);">CLICK ME!</div>
  <div ng-click="$window.location.href='http://test.com';">DIRECTT LINK!</div>
</div>

为什么第二个div在点击时什么都不做?

NB。

我不需要在弹出窗口或新窗口中打开链接,我的div已经在弹出窗口中,所以我只需要像a href一样在同一个窗口中打开该链接,我所需要的。

换句话说,我需要在不使用“a href”的情况下打开链接。 URL在生成的HTML中,所以我不能将url放在javascript中,这是一个独立的文件......

2 个答案:

答案 0 :(得分:2)

您的代码无效,因为html无法识别$ window 在html中尝试这个

    <div ng-app="myApp" ng-controller="testCtrl">
      <div data-href="http://test.com" ng-click="myAlert($event);">CLICK ME!</div>
      <div ng-click="openLink('http://test.com');">DIRECTT LINK!</div>
    </div>
脚本中的

    var myApp = angular.module('myApp', []);

    myApp.controller('testCtrl', ['$scope', '$window', function($scope, $window) {
      $scope.greeting = 'Hola!';
      $scope.myAlert = function(event) {
        console.log('this is the $scope.greeting');
        console.log($scope.greeting);
        console.log('this is the $window.location.href:');
        console.log($window.location.href);
        console.log('this is the event.target.dataset.href:');
        console.log(event.target.dataset.href);   
        $window.location.href = event.target.dataset.href;
      }

      $scope.openLink = function(link){
        $window.location.href = link;
      };

    }]);

答案 1 :(得分:0)

使用<div onclick="window.location.replace('http://test.com')"></div>