在带有 $index 的 ng-repeat 中使用 ng-click
Using ng-click in ng-repeat with $index
我正在尝试在 div 上使用 ng-click 和 ng-repeat 元素使用 $index 如下所示:
HTML:
<div class="elementContainer" ng-repeat="element in elements" ng-click="elementUrl($index)">
<h2>{{ element.name }}</h2>
<p><strong>{{ element.description }}</strong></p>
</div>
JS文件:
var app = angular.module('portfolioapp', []);
app.controller('MainController', ['$scope', function($scope) {
$scope.elements = [
{
"name": "1",
"description": "abcd"
},
{
"name":"2",
"description": "lmno"
},
{
"name": "3",
"description": "xyz"
}
]
$scope.elementUrl = function(index) {
if (index == 0) {
$window.location.href = 'first path';
}
else if (index == 3) {
$window.location.href = 'second path';
}
};
}]);
当我点击 div (.elementContainer) 时,网页没有重定向到指定路径(本地路径)。
我哪里做错了?
提前致谢。
为了在你的控制器中使用 $window
,你应该注入它
app.controller('MainController', ['$scope', '$window', function($scope,$window) {
或另一种方式:使用window
,注意:没有$
符号,而不是$window
我正在尝试在 div 上使用 ng-click 和 ng-repeat 元素使用 $index 如下所示:
HTML:
<div class="elementContainer" ng-repeat="element in elements" ng-click="elementUrl($index)">
<h2>{{ element.name }}</h2>
<p><strong>{{ element.description }}</strong></p>
</div>
JS文件:
var app = angular.module('portfolioapp', []);
app.controller('MainController', ['$scope', function($scope) {
$scope.elements = [
{
"name": "1",
"description": "abcd"
},
{
"name":"2",
"description": "lmno"
},
{
"name": "3",
"description": "xyz"
}
]
$scope.elementUrl = function(index) {
if (index == 0) {
$window.location.href = 'first path';
}
else if (index == 3) {
$window.location.href = 'second path';
}
};
}]);
当我点击 div (.elementContainer) 时,网页没有重定向到指定路径(本地路径)。
我哪里做错了?
提前致谢。
为了在你的控制器中使用 $window
,你应该注入它
app.controller('MainController', ['$scope', '$window', function($scope,$window) {
或另一种方式:使用window
,注意:没有$
符号,而不是$window