无法在ng-reapeat中设置AngularJS变量

时间:2017-07-28 06:40:15

标签: javascript angularjs

我想实现只有在点击后才能完全看到的列表。 但是当我尝试在ng-click上设置值时,值范围仅在单击的元素上。

<ul data-ng-init="showIataList = false">
  {{showIataList}} <-- always false :( but should be true after click on link from list
  <li data-ng-repeat="value in data.departureIataList">
    <a href="javascript:"
       data-ng-if="$index < 3 || showIataList">
       {{value}}
    </a>
    {{showIataList}}
    <a href="javascript:"
       data-ng-if="!showIataList && $index == 3"
       data-ng-click="showIataList = true">
        {{showIataList}} <-- after click is true, but true should be and on the top showIataList variable
    </a>
  </li>
</ul>

2 个答案:

答案 0 :(得分:3)

仅供参考,每个ng-repeat项目都有自己的范围。这就是data-ng-click="showIataList = true"适用于特定范围而不是主$scope

的原因

您可以编写例如:

$scope.data.showIataList = false;

一切都会有效

或在您的情况下:<ul data-ng-init="data.showIataList = false">

Fiddle Demo

答案 1 :(得分:1)

问题在于这个标签。它有ng-if,所以它创建一个新的范围并从父范围继承数据。

ngIf

由于showIataList继承自父级,因此您的ngIf也会复制到parentScope.showIataList = ngIf.showIataList

ngIf.showIataList

但点击链接后,parentScope.showIataList已更改,但该更改不会传播到showIataList(因为ngIf是(原始值)

为什么你看到showIataList内部,parentScope是真的,但在<ul data-ng-init="iataList = {isShow:false}"> {{iataList.isShow}} <li data-ng-repeat="value in data.departureIataList"> <a href="javascript:" data-ng-if="$index < 3 || iataList.isShow"> {{value}} </a> {{showIataList}} <a href="javascript:" data-ng-if="!iataList.isShow&& $index == 3" data-ng-click="iataList.isShow= true"> {{iataList.isShow}} </a> </li> </ul> 中它仍然是假的。

您可以通过将showIataList移动​​到这样的对象来修复它。

    HashMap<String, String> header = new HashMap<String, String>();
    header.put("Content-type", "application/json");
    HashMap<String, String> data = new HashMap<String, String>();
    data.put("comments", comments);
    data.put("quantity", quantity);
    data.put("retailerId", retailerID);
    data.put("retailerquote", retailerQuote);
    data.put("wholesalerId", wholesalerID);
    data.put("unit", unit);
    data.put("subProductId", subProductID);

    // edited here
    Gson gson = new Gson();
    String jsonString = gson.toJson(data);
    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonString);
    Call<RequestQuoteCheck> call = RetrofitBaseAdapter.getCommonPathInterfaceRequestQuote().requestQuoteCheck(body);

    call.enqueue(new retrofit2.Callback<RequestQuoteCheck>() {

        @Override
        public void onResponse(Call<RequestQuoteCheck> call, Response<RequestQuoteCheck> response) {

            Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFailure(Call<RequestQuoteCheck> call, Throwable t) {

        }
    });