简体   繁体   English

从href调用angularjs范围函数

[英]Calling angularjs scope function from href

I am using a library which appends a href element onto an tag. 我正在使用一个库,它将href元素附加到标记上。 On this link I need to make a call to an angularjs function that is within scope. 在这个链接上,我需要调用范围内的angularjs函数。 Something like... 就像是...

<a href="{{someFunction()}}"></a>

Note: I am attaching this href via javascript from another library (nvd3.js) not actually writing this in because if I was I could easily use ng-click or ng-href. 注意:我通过javascript从另一个库(nvd3.js)附加此href,实际上没有写入,因为如果我是,我可以轻松地使用ng-click或ng-href。

So I was not pleased with the answer to this as it doesn't really utilize an elegant angular solution. 所以我对这个答案并不满意,因为它并没有真正使用优雅的角度解决方案。

Here's my solution: http://jsfiddle.net/jjosef/XwZ93 这是我的解决方案: http//jsfiddle.net/jjosef/XwZ93

HTML: HTML:

<body class="wrapper" ng-app="ExampleApp">
  <a my-href="buildUrl('one', aVariable, 'three')">This is my a tag with a function that builds the url</a>
</body>

JS: JS:

angular.module('ExampleApp', []);
angular.module('ExampleApp').run(function($rootScope) {
  $rootScope.buildUrl = function() {
    var link = [];
    for(var i = 0; i < arguments.length; i++) {
      link.push(arguments[i].toLowerCase());
    }
    return '/#!/' + link.join('/');
  };

  $rootScope.aVariable = 'two';
});

angular.module('ExampleApp').directive('myHref', function($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var url = $parse(attrs.myHref)(scope);
      element.attr('href', url);
    }
  }
});

That's a bit convoluted. 这有点令人费解。

CAVEAT : This is very, very hacky and just absolutely exactly what you're NOT supposed to do in angular, but I guess you know that and the library is making your life hard... CAVEAT :这非常,非常hacky,绝对正是你应该做的角度,但我猜你知道这个和图书馆让你的生活变得艰难......

First, unlike onclick , an href won't interpret a string as javascript. 首先,与onclick不同, href不会将字符串解释为javascript。 Instead, you'd have to use 相反,你必须使用

<a href="javascript:someFunction()"></a>

But this alone won't make it work, because someFunction() is not a method on the document , but on the controller, so we need to get the controller first: 但是这一点不会使它工作,因为someFunction()不是document上的方法,而是在控制器上,所以我们需要先得到控制器:

<a href="javascript:angular.element(
         document.getElementById('myController')).scope().someFunction();"></a>

Where myController refers to the DOM element that is decorated with ng-controller , eg myController引用用ng-controller修饰的DOM元素,例如

<div data-ng-controller="SomeController" id="myController"> ... </div>

If someFunction modifies the state of the view, you'll also need to use $scope.apply , ie 如果someFunction修改了视图的状态,你还需要使用$scope.apply ,即

<a href="javascript:angular.element(document.getElementById('myController')).
           scope().$apply(someFunction)"></a>

Note that you don't need the {{ }} syntax, because you're calling javascript directly, you're not asking angular to modify your markup. 请注意,您不需要{{ }}语法,因为您直接调用javascript,而不是要求angular修改标记。

您应该使用ng-click这里。

The simplest solution is 最简单的解决方案是

<a href="" ng-click="someFunction(x,y,z)">Go</a>

href="" is important, otherwise hover cursor style does not change to a pointer href =“”很重要,否则悬停光标样式不会更改为指针

使用{{someFn}}时,您需要使用$ parse()来处理标记。

I mixed some things here and I have it working. 我在这里混合了一些东西,我有它的工作。

I have a menu with some options, each one calls a different method on the controller. 我有一个带有一些选项的菜单,每个选项在控制器上调用不同的方法。

<span ng-show="hoverOptions" ng-mouseleave="hoverOut()" class="qk-select ui-select-container qk-select--div">
    <ul>
        <li ng-repeat="option in menuOptions"><a href="javascript:void(0);" ng-click="callFunction(option.action)">{{option.name}}</a></li>
    </ul>
</span>

The callFunction method in the controller is defined like that: 控制器中的callFunction方法定义如下:

$scope.callFunction = function (name){
      if(angular.isFunction($scope[name]))
                $scope[name]();
}

And the menu options are defined also in the controller in that way: 菜单选项也以这种方式在控制器中定义:

$scope.menuOptions = [{action: "uploadPhoto" , name:"Cargar foto"}, {action: "logout", name:"Cerrar sesión"}, {action: "createUser", name:"Nuevo usuario"}];

Hope it helps someone. 希望它可以帮助某人。

solution: https://embed.plnkr.co/bhMcEO/ 解决方案: https//embed.plnkr.co/bhMcEO/

<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8" />
      <title>$window or $location to Redirect URL in AngularJS</title>
      <link rel="stylesheet" href="style.css" />
      <script src="https://code.angularjs.org/1.4.1/angular.js"></script>
      <script>
        var app = angular.module('RedirectURLApp', []);
        app.controller('RedirectURLCtrl', function($scope, $window) {
          $scope.name = 'Anil';
          $scope.RedirectToURL = function() {
            var host = $window.location.host;
            var landingUrl = "http://www.google.com";
            alert(landingUrl);
            $window.location.href = landingUrl;
          };
        });
      </script>
    </head>
    <body ng-app="RedirectURLApp">
      <div ng-controller="RedirectURLCtrl">
        <h2>$window or $location to Redirect URL in AngularJS</h2>
        <p>Hello {{name}},</p>
        Click to Redirect <a href="" ng-click="RedirectToURL()">Click Me!</a>
      </div>
      <div><h4><a href="http://www.code-sample.com/2015/06/redirect-to-new-page-using-location-or.html">For more detail..</a></h4></div>
    </body>
    </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM