在尝试访问参数

时间:2016-12-29 05:16:25

标签: javascript angularjs

我正在尝试访问传递给JavaScript函数的参数并提醒值。但当我提醒我的价值时,undefined处于警戒状态。我在这里做错了什么。

HTML

<div ng-app="plusminusApp" ng-controller="categorylist">        
    <div class="whitescreen" id="buttons-overlay">
        <div class="icons-container">
            <div class="icons-inside-container">
            <div ng-repeat="category in categories" value="{{category.picture}}" class="category-icon-thumbnail" onclick="setCategory(this.value);">
                        <img value="{{category.category}}" src="{{category.picture}}">
            </div>
            </div>
        </div>
    </div>
</div>

app.js

function setCategory(category){
    alert(category)
    document.getElementById('buttons-overlay').style.display = 'none';
}

3 个答案:

答案 0 :(得分:2)

如果要将角度范围值传递给函数,则必须为ng-前缀事件。您不能将范围变量传递给角度上下文之外的函数。

      <div ng-repeat="category in categories" value="{{category.picture}}" class="category-icon-thumbnail" ng-click="setCategory(category.picture)">

并且该函数必须在控制器的范围内,这意味着您需要定义$scope.setCategory = function(val){}

答案 1 :(得分:0)

HTML:

<div ng-app="plusminusApp" ng-controller="categorylist">        
<div class="whitescreen" id="buttons-overlay">
    <div class="icons-container">
        <div class="icons-inside-container">
        <div ng-repeat="category in categories"class="category-icon-thumbnail" >
            <img value="{{category.category}}" src="{{category.picture}}" ng-click="setCategory(category.picture);">
        </div>
        </div>
    </div>
</div>

JS:

$scope.setCategory = function(val){
     console.log(val)
 }

答案 2 :(得分:0)

假设这是你的json

$scope.categories = [{
    'category': 'ABC',
    'picture': 'https://randomuser.me/api/portraits/men/22.jpg'
  }, {
    'category': 'ced',
    'picture': 'https://randomuser.me/api/portraits/men/13.jpg'
  }]

使用以下代码

$scope.setCategory =function(category) {
    $scope.something=category;

    document.getElementById('buttons-overlay').style.display = 'none';
  }



<div ng-app="plusminusApp" ng-controller="categorylist">
    <p>Hello!</p>
    <div class="whitescreen" id="buttons-overlay">
      <div class="icons-container">
        <div class="icons-inside-container">
          <div ng-repeat="category in categories" value="{{category.picture}}" class="category-icon-thumbnail">
            <button ng-click="setCategory(category.category)"> {{category.category}}
            </button>
            <img value="{{category.category}}" src="{{category.picture}}">
          </div>
        </div>
      </div>

    </div>
  </div>

为了简单和理解的目的,我已将click事件从div更改为button。

LIVE DEMO