在检索数据之前运行Angular ng-repeat过滤器

时间:2015-04-22 21:53:59

标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-filter

我有一份工作人员需要过滤的约会清单。我正在使用Breeze控制器从数据库中提取约会。有些预约涉及多名工作人员,因此我需要深入了解预约的子实体,以便为每次预约找到工作人员。我试图根据其他地方使用ng-repeat和过滤器选择的工作人员显示一个列表,如下所示:

<section data-ng-repeat="appt in apptCtrl.appointmentList | filter: apptCtrl.matchStaff(staff)" data-ng-model="apptCtrl.appointmentList" class="apptStaffList">
    <appt-event data-ng-model="appt"></appt-event>
</section>

我的约会控制器上的过滤功能如下:

self.matchStaff = function (query) {
    var staffAppts = [];
    angular.forEach(self.appointmentList, function (a) {
        var staffAppt = a.some(function (s) {
            return s.StaffId === query;
        });
        if (staffAppt) {
            staffAppts.push(a);
        }
    });
    return staffAppts;
};

不幸的是,在初始化控制器时会填充self.appointmentList,但直到视图加载后列表才会返回。如果没有过滤器,则只要填充列表,就会显示约会。但是,当调用matchStaff时,self.appointmentList只是一个空数组。

有没有办法在填充列表后使过滤器运行?还有其他方法来处理过滤器吗?在这种情况下,有没有办法用字符串调用过滤器?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果您在应用程序中使用路由,则可以使用resolve方法加载appointmentList。

FATAL EXCEPTION: main
    Process: edu.gannon.gannonknightnews, PID: 3083
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
            at edu.gannon.gannonknightnews.MenuFragment$GetNews$CustomAdapter.getView(MenuFragment.java:197)


import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class MenuFragment extends Fragment {
    private ProgressDialog pDialog;// Progress Dialog
    ListView newsList;
    String my_url;
    ArrayList<HashMap<String, String>> postList; //Declare Array
    private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/";
    GetNews.CustomAdapter CA;

    // JSON Node names
    private static final String TAG_ID = "id";
    private static final String POST_ALLPOSTS = "posts";
    private static final String POST_ID = "ID";
    private static final String POST_TITLE = "post_title";
    private static final String POST_CONTENT = "post_content";
    private static final String GUID = "guid";

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view =  inflater.inflate(R.layout.home, container, false);
        newsList = (ListView) view.findViewById(R.id.homeListView);
        TextView topic = (TextView) view.findViewById(R.id.topic);
        postList = new ArrayList<HashMap<String, String>>();
        //Get arguments
        Bundle args = getArguments();
        String mytopic = args.getString("Topic");
        getActivity().getActionBar().setTitle("GannonKnightNews");
        //Set topic
        topic.setText(mytopic.toUpperCase());
        //Execute getContacts
        new GetNews().execute();

        return view;
    }

    //Async Task
    private class GetNews extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            Log.d("Strings", "Checking Json");
            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // contacts JSONArray
                    JSONArray posts = null;
                    // Getting JSON Array node
                    posts = jsonObj.getJSONArray(POST_ALLPOSTS);

                    // looping through All Contacts
                    for (int i = 0; i < posts.length(); i++) {

                        JSONObject c = posts.getJSONObject(i);
                        Log.d("Post->",posts.getJSONObject(i).toString());

                        String id = c.getString(POST_ID);

                        Log.d("Post->ID",id);
                        String post_title = c.getString(POST_TITLE);
                        String post_content = c.getString(POST_CONTENT);
                        String guid = c.getString(GUID);
                        Log.d("GUID->",guid);

                        //String gender = c.getString(TAG_GENDER);

                        // tmp hashmap for single post
                        HashMap<String, String> post = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        post.put(POST_ID, id);
                        post.put(POST_TITLE, post_title);
                        post.put(POST_CONTENT, post_content);
                        post.put(GUID, guid);
                        post.put("ListCount",String.valueOf(i));

                        // adding contact to contact list
                        postList.add(post);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            // Updating parsed JSON data into ListView
               /*
            ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
                    new String[] { POST_TITLE,POST_CONTENT, GUID },
                    new int[] {R.id.email, R.id.mobile, R.id.guid });

            newsList.setAdapter(adapter);
            */
            CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
            newsList.setAdapter(CA);
        }
        public class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {

            private final ArrayList<HashMap<String, String>> objects;

            public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
                //something is wrong with super
                super(context, resource, objects);
                this.objects = objects;
            }
            public View getView(int position, View convertView, ViewGroup Parent){
                //convertView = new ImageView();
                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item,null);

                }

                android.widget.ImageView postImage = (android.widget.ImageView) convertView.findViewById(R.id.img);
                int getListPos = newsList.getFirstVisiblePosition();
                //i set the count starting 0 and saved in the hashmap array
                //to compare the first result with the first position of listview

                int count = Integer.parseInt(objects.get(position).get("ListCount"));
                my_url = objects.get(position).get(GUID);
                if(getListPos == count) {
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.list_item_header,null);
                    TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
                    TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
                    HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
                    HeaderContent.setText(objects.get(position).get(POST_CONTENT));
                    if(objects.get(position).get(GUID).equals("NULL")) {
                        postImage.setImageResource(R.drawable.default_bg);
                    }else{
                        new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
                    }
                }
                else{
                    //CHoose list item
                    //************************************************
                    //THe problem is in this textview which gives null object reference error
                    TextView thisview = (TextView) convertView.findViewById(R.id.email);
                    Log.d("Title", String.valueOf(thisview.getText()));
                    TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
                    thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
                    postContent.setText(objects.get(position).get(POST_CONTENT));
                    if(objects.get(position).get(GUID).equals("NULL")) {
                        postImage.setImageResource(R.drawable.default_bg);
                    }else{
                        new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
                    }
                }

                return convertView;
            }


        }//Custom Adapter

    }//END getnews Async Task

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }//

}

...

//config
    $routeProvider
        .when('/',
        {
          templateUrl: "app.html",
          controller: "AppCtrl"
          resolve: {
            appointments: function (myAppoimentsService) {
              return myAppoimentsService.fetch();
            }
          }
        }