为什么 ng-click 无法发送用大括号 {{ }} 括起来的函数参数

Why ng-click is unable to send function parameter which is embraced with curly {{ }} brackets?

本文关键字:参数 函数 起来 ng-click 为什么      更新时间:2023-09-26

我想通过调用函数来发送路径,通过将路径作为函数参数发送。

但是我的控制器代码:

$scope.go = function(path){
    alert(path); //show the path comes in as parameter
    $location.path( path );
  }

我的视图代码 (.html)

<button ng-click="go('/hotellist/{{topHeading}}?tab=packages')" ></button>

我已经检查了它是否正确获取{{topheading}} $scope.topheading的值,但是当我使用 ng-click 发送它时,它根本没有任何价值!警报只是说'/hotelist/?tab=packages'.

知道吗?为什么会这样?

试试

<button ng-click="go('/hotellist/' + topHeading + '?tab=packages')" ></button>

在按钮上单击尝试:

<button ng-click="go('/hotellist/'+topHeading+'?tab=packages')" ></button>

首先,如果你打算在你的应用程序中做很多事情,你应该看看ui-router,它会对你有很大帮助。

其次,您是否尝试过让方法返回 url:

<button ng-click="vm.packagesPath()"></button>

在控制器中:

packagesPath() {
  return `/hotellist/${$scope.topHeading}?tab=packages`;
}  

你的topHeading显然会在范围内。试试看,看看它是否有效。

试试这个,

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$location) {
$scope.topHeading = "test";  
$scope.go = function(path){
    console.log(path);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <body ng-app="plunker" ng-controller="MainCtrl">
   <button ng-click="go('/hotellist/'+topHeading+'?tab=packages')">GO</button>
    
  </body>

你不能像这样发送范围变量。在 ng 单击中仅使用topheading

您不需要在 ngClick 中使用括号。正确的方法是:

<button ng-click="go('/hotellist/topHeading?tab=packages')"></button>

它不起作用,因为该范围变量中没有值。我尝试了这段代码,它有效。

首先,我使用 ng-init 使用另一个函数设置了 Scope 变量值。然后我在 ng-click 中使用该值。

.HTML

<div ng-app="myApp" ng-controller="myCtrl" ng-init="SetScopeVariable()">
Name: <input type="button" ng-click="getPath('/hotellist/'+topHeading+'?tab=packages')">

脚本

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.SetScopeVariable=function(){
$scope.topHeading='123';
}
$scope.getPath=function(path){
alert(path);
}
});