-1

Filter In AngularJS With Rails Application

Filter In AngularJS With Rails Application

In this article, I want to show you guy about filter in angularjs, It is very important before this you need to know about basic of angularjs controller and model. By other hand you can image your self about that it is easy to handle the code.

title.png

What is Filter ?

With the simple meaning of filter is filter can be added in AngularJS to format data. In angularjs provides filters to transform data:

  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an array.
  • json Format an object to a JSON string.
  • limitTo Limits an array/string, into a specified number of elements/characters.
  • lowercase Format a string to lower case.
  • number Format a number to a string.
  • orderBy Orders an array by an expression.
  • uppercase Format a string to upper case.

Filter with Expression

You can add fitler to your code angularjs by using expression with the pipe character | , followed by a filter Example:

with The uppercase filter format strings to upper case:

<div ng-app="myExample" ng-controller="personCtrl">
  <p>The name is {{ lastName | uppercase }}</p>
</div>

Filter with Directive

Filter are added to directives, like ng-repeat, by using the pipe | , followed by a filter, Example with the orderby fitler sort an array:

<div ng-app="myApp" ng-controller="namesCtrl">
    <ul>
      <li ng-repeat="x in names | orderBy:'country'">
        {{ x.name + ', ' + x.country }}
      </li>
    </ul>
 </div>

With Ruby On Rails

But now let's start around with Ruby on Rails with filter in angular to search data . Create new project in ruby on rails

 $ rails new tuktuk_project

After you create a application above, switch to its folder:

$ cd tuktuk_project

after that we create product controller and model

$ rails g controller product
$ rails g model product

we continue add other column in model product.

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.integer :price
      t.integer :discount
      t.text :description
      t.integer :sex
      t.references :brand, index: true
      t.references :type
      t.references :media_art

      t.timestamps null: false
    end
  end
end

So you need to run:

$ rake db:migrate

now we need to add angularjs to our application, we decide to using bower to install angularjs in our rails application.

$ bower init

You need to install bower in your computer, because with bower, you can install angular by other hand. After you runbower init. You will see in your project rails with have file: bower.json

{
  "name": "tuktuk_project",
  "homepage": "https://github.com/samnangcattor/tuktuk_project",
  "authors": [
    "samnangcattor <kcattor@gmail.com>"
  ],
  "description": "tuk tuk online shopping",
  "main": "",
  "license": "MIT",
  "private": true,
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "bootstrap": "^3.3.7",
    "angular": "^1.5.8",
    "angular-route": "^1.5.8",
    "angular-resource": "^1.5.8"
  }
}

With your application, You can see other different from my bower.json (it depends by your property). To use bower with rails application you need to do as below: create file.bowerrc in your application.

{
  "directory": "vendor/assets/components"
}

To use bower with rails application we need to add more js of bower to our asset rails in config/application.rb

require File.expand_path("../boot", __FILE__)

require "rails/all"

# Require the gems listed in Gemfile, including any gems
# you"ve limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module TuktukProject
  class Application < Rails::Application
    config.assets.paths << Rails.root.join("vendor", "assets", "components")
    config.active_record.raise_in_transactional_callbacks = true
  end
end

After we add angular in our application:

$ bower install bootstrap --save
$ bower install angular --save
$ bower install angular-route --save
$ bower install angular-resource –save

With code above you can create required dependencies for our project in directory components and save it in JSON. Add require for javascript rails application app/assets/javscripts/application.js

//= require bootstrap/dist/js/bootstrap.min
//= require angular/angular.min
//= require angular-route/angular-route
//= require angular-resource/angular-resource

Our design model, we want to create complex model to query in this project, so we create more 3 model that related with product.

 $ rails g model brand
 $ rails g model type
 $ rails g model media_art

With these model above, we add column “name” and related with product with one - one

database.png

In our product controller app/controllers/products_controller.rb, we need to edit more code:

class ProductsController < ApplicationController
  def index
    @products = Product.all
    respond_to :html, :json
  end
end

We create repond_to :json to create file json file for our angular required. Create our view: app/views/products/index.html.erb

<div class="panel panel-default">
  <div class="panel-heading"><h3 class="panel-title">Filter<h3></div>
  <div class="panel-body">
    <ul class="nav nav-pills nav-stacked">
      <li>
        <div class="radio">
          <label class="radio-inline"><input type="radio" name="optradio" value="male" ng-model="search.sex"><%= t ".sex.male" %></label>
          <label class="radio-inline"><input type="radio" name="optradio" value="female" ng-model="search.sex"><%= t ".sex.female" %></label>
        </div>
      </li>
      <li>
        <div class="form-group">
          <label for="sel1"><%= t ".select_brand" %></label>
          <select class="form-control" id="sel1" ng-model="search.brand.name">
            <option ng-repeat="brand in brands">{{brand.name}}</option>
          </select>
        </div>
      </li>
      <li>
        <div class="form-group">
          <label for="sel1"><%= t ".select_type" %></label>
          <select class="form-control" id="sel1" ng-model="search.type.name">
            <option ng-repeat="type in types">{{type.name}}</option>
          </select>
        </div>
      </li>
      <li>
        <div class="form-group">
          <label for="sel1"><%= t ".select_media_art" %></label>
          <select class="form-control" id="sel1" ng-model="search.media_art.name">
            <option ng-repeat="media_art in media_arts">{{media_art.name}}</option>
          </select>
        </div>
      </li>
      <li>
        <div class="form-group">
          <label for="sel"><%= t ".min_price" %></label>
          <select class="form-control" id="sel1" ng-model="filterModelMin.price">
            <% Product::PRICE_RANGE.each do |price| %>
              <option><%= price %></option>
            <% end %>
          </select>
          <label for="sel"><%= t ".max_price" %></label>
          <select class="form-control" id="sel2" ng-model="filterModelMax.price">
            <% Product::PRICE_RANGE.each do |price| %>
              <option><%= price %></option>
            <% end %>
          </select>
        </div>
      </li>
    </ul>
  </div>

Now afer we code our view, we need to code our javascript to handle filter. Create app/assets/javascripts/controllers/search.js

(function() {
  var shopApp = angular.module("shoppingOnline", ["ngRoute", "ngResource"]);

  shopApp.controller("ProductController", ["$scope", "$http", function($scope, $http){
    $http.get("/products.json").success(function(data, status, headers, config) {
      $scope.products = data;
    }).error(function(data, status, headers, config) {
      // log errors
    });

    $scope.byPrice = function (fieldName, minValue, maxValue) {
      if (minValue === undefined) minValue = Number.MIN_VALUE;
      if (maxValue === undefined) maxValue = Number.MAX_VALUE;

      return function predicateFunc(item) {
        return minValue <= item[fieldName] && item[fieldName] <= maxValue;
      };
    };
  }]);
})();

However we need to get data from our url http://localhost:3000/products.json, so you need to create view with product.json. We create file app/views/products/_product.json.jbuilder and edit code:

json.extract! product, :id, :name, :discount, :description, :price, :sex, :images, :brand, :type, :media_art
json.url product_url product, format: :json

And to show view app/views/products/_product.json.jbuilder with our product controller with function index, we need to add more /app/views/products/index.json.jbuilder with code:

json.array! @products, partial: "products/product", as: :product

Now you can filter, data with angularjs.

Conclusion

However this article it is very useful for you guy that want to use filter angularjs with ruby on Rails. By other hand this article is just simple tutorial, we think it is easy for you guy to use and do in your project if you need.

Documentation


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí