搜索过滤器 - Twig 循环内的 Angular Js [英] Search Filter - Angular Js inside Twig loop

查看:21
本文介绍了搜索过滤器 - Twig 循环内的 Angular Js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Angular JS,因为对于像我这样的初级开发人员来说,它的学习曲线似乎很陡峭.我创建了 angular 文件并使用这个 $interpolateProvider 提供程序来处理 twig 标记/语法.

var customApp = angular.module('customApp', []);customApp.config(function($interpolateProvider) {$interpolateProvider.startSymbol('//');$interpolateProvider.endSymbol('//');});customApp.controller('customController', function($scope) {$scope.message = '好的 symfony2';});

现在看来,这很容易

 

<input type="text" ng-model="message"/>//信息//

现在我希望它像这样用于搜索机制

 

搜索 <input type="text" placeholder="search your name" ng-model="searchText"/><br/>

使用 Angular ng-repeat 指令,我可以在循环中使用它

 
{% for employee in雇员 %}<tr {% if loop.index isodd %}class="color"{% endif %}><td>{{employee.name }}</td><td>{{employee.lastname }}</td></tr>{% 结束为 %}

这里如何使用 Angular 搜索过滤器?

 {% for employee in雇员 |过滤器:搜索文本 %}......

Twig 在这里抱怨...

更新

当我深入研究 Symfony 文档时,我明白为了让 Angular JS 从数据库中获取数据,我必须创建一个服务或控制器,然后由 angular 调用

emp.yml

emp_angular:路径:/emps-角度默认值:{ _controller:捆绑:Emp:emp_angular"}

控制器

公共函数 emp_angularAction(Request $request){$names= array();//$em = $this->getDoctrine()->getManager();//$datas = $em->getRepository('Bundle:Voters')->getAllVotersDesc();$datas = array('manila','quezon','pasig','makatis');用于测试的临时数据//转储($数据);foreach ($datas 作为 $data){$names[] = $data;}$response = new JsonResponse();$response->setData($names);返回 $response;//return $this->render('Bundle:Emp:data.html.twig', array(//'名字' =>$响应,//));}

有了这个,我就可以成功拉取数据了

["manila","quezon","pasig","makatis"]

但是我真的很困惑 Angular 如何获取 url

customApp.controller('customController', function($scope,$http) {$scope.message = '好的 symfony2';$http({method:'GET',url:'{{ path('emp_angular')}}'}).success(function(response){$scope.names = 响应;});

});

此文件不返回任何内容

在普通的php中,$http里面的url是这样调用的

$http({method:'GET', url:'page2.php'}).success(function(response){$scope.names = 响应;

其中 page2.php 是从数据库中检索数据的文件

如何在 Angular 中使用它?

更新

几乎做到了,仅剩 1 个问题..

我在这里重构我的代码

视图

{% 扩展 '::base.html.twig' %}{% 块体 -%}<div ng-app="myApp" ng-controller="customersCtrl">//名称//<table ng-model="names"><tr ng-repeat="x 名称"><td>//x.id//</td><td>//x.name//</td></tr>{% 结束块 %}{% 阻止 javascripts %}{{ 父母()}}<script src="//code.angularjs.org/1.4.8/angular.js"></script><脚本>var app = angular.module('myApp', []);app.config(function($interpolateProvider) {$interpolateProvider.startSymbol('//');$interpolateProvider.endSymbol('//');});app.controller('customersCtrl', function($scope, $http) {//$http.get("http://localhost:8093/voters/voters_angular")$http.get("{{ path('emp_angular') }}").success(function (data,status, headers, config) {$scope.names = data;});});//console.log(names);{% 结束块 %}

此路由文件

 emp_angular:路径:/选民角度默认值:{ _controller: "Bundle:Voters:voters_angular" }角度:路径:/角度默认值:{ _controller:捆绑:选民:角度"}

重构控制器

 公共函数voters_angularAction(Request $request){$names = array();$em = $this->getDoctrine()->getManager();$entities = $em->getRepository('Bundle:City')->createQueryBuilder('c')-> orderBy('c.name', 'ASC')->getQuery()->getResult();foreach ($entities 作为 $entity){$names[] = $entity->getName();}$response = new JsonResponse();$response->setData($names);返回 $response;}公共函数 angularAction(Request $request){return $this->render('Bundle:Voters:data.html.twig');}

在树枝上

//名字//

成功显示数据

 ["Aborlan","Abra de Ilog","Abucay","Abulug","Abuyog","Adams"]

如何将其转换为字符串?

但是 ng-repeat 指令在这里不起作用

<td>//x.id//</td><td>//x.name//</td></tr>

对此有什么可能的解决方法?symfony 控制器本身有问题吗?

解决方案

你的代码几乎可以工作了.ng-repeat 指令不工作的原因是

<td>//x.name//</td></tr>

因为在你的 symfony 控制器中,你已经循环了你的结果,所以改为使用

 <td>//x//</td></tr>

让我们重构你的角度控制器

现在你的观点

{% 块体 -%}<div ng-app="myApp" ng-controller="customersCtrl"><table ng-model="names" class="table"><头><tr><th>全名</th></tr></thead><tr ng-repeat="x in names track by $index"><td>//x//</td></tr></tbody>

{% 结束块 %}

您可能想知道为什么在您的 ng-repeat 指令中我将您的代码更改为

 <td>//x//</td></tr>

您之前提到过您需要大量数据,并且可能会出现重复数据,因此请防止出现该错误,

 按 $index 跟踪

按此处所述添加

链接

I am playing around Angular JS as it seems that its learning curve is steep for a junior developer like me.I created angular file and use this $interpolateProvider provider in order to work with twig markup/syntax.

var customApp = angular.module('customApp', []);

  customApp.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('//');
  $interpolateProvider.endSymbol('//');
 });

  customApp.controller('customController', function($scope) {
   $scope.message = 'Ok symfony2';
 });

Now in view, that's easy

 <div ng-app="customApp" ng-controller="customController">
    <input type="text" ng-model="message" />
      // message //
 </div>

Now I want this to use in search mechanism like so

 <div ng-app="customApp" ng-controller="customController">
    Search <input type="text" placeholder="search your name" ng-model="searchText" /><br />
 </div>

Using Angular ng-repeat directive, I can use it in loop something like

 <tr ng-repeat="employee in employees | filter:searchText>
   <td>//employee.name//</td>
   <td>//employee.lastname//</td>
 </tr>

Now my problem is, the data is dynamically 'fetch' from database and I displaying it using Twig's for loop

{% for employee in employees %}
  <tr {% if loop.index is odd %}class="color"{% endif %}>
     <td>{{ employee.name }}</td>
     <td>{{ employee.lastname }}</td> 
  </tr>
{% endfor %}

How to use the Angular search Filter here?

 {% for employee in employees | filter:searchText %}
 ......

Twig is complaining here...

update

As i dig deeper into Symfony docs, I understand that inorder for the Angular JS fetch the data from database, I have to create a service or controller which then called by angular

emp.yml

emp_angular:
path: /emps-angular
defaults: { _controller: "Bundle:Emp:emp_angular" }

Controller

public function emp_angularAction(Request $request)
{
    $names= array();
    //$em = $this->getDoctrine()->getManager();

    //$datas = $em->getRepository('Bundle:Voters')->getAllVotersDesc();

    $datas = array('manila','quezon','pasig','makatis');temp data for testing
   // dump($data);

   foreach ($datas as $data)
    {
        $names[] = $data;
    }

    $response = new JsonResponse();
    $response->setData($names);
     return $response;
   // return $this->render('Bundle:Emp:data.html.twig', array(
      //  'names' => $response,
    //));
}

with this, I can pull the data successfully

["manila","quezon","pasig","makatis"]

However I really confused on how Angular fetch the url

customApp.controller('customController', function($scope,$http) {
$scope.message = 'Ok symfony2';
$http({method:'GET',url:'{{ path('emp_angular')}}'}).success( function(response){
    $scope.names = response;
});

});

This file doen't return anything

In plain php, The url inside $http is called like this

$http({method:'GET', url:'page2.php'}).success(function(response){
$scope.names = response;

Where page2.php is the file that retrieves data from database

How to use this in Angular?

Update

Almost did it, only 1 remaining problem..

I refactor my codes here

The view

{% extends '::base.html.twig' %}

{% block body -%}

<div ng-app="myApp" ng-controller="customersCtrl">
 //names //
<table ng-model="names">
  <tr ng-repeat="x in names">
    <td>//x.id//</td>
    <td>//x.name//</td>
  </tr>
</table>

{% endblock %}

{% block javascripts %}
 {{ parent() }}
  <script src="//code.angularjs.org/1.4.8/angular.js"></script>
  <script>
    var app = angular.module('myApp', []);

    app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
    });

    app.controller('customersCtrl', function($scope, $http) {
        //$http.get("http://localhost:8093/voters/voters_angular")
        $http.get("{{ path('emp_angular') }}")
        .success(function (data,status, headers, config) {$scope.names = data;});
    });
    //console.log(names);
 </script>  
 {% endblock %}

The route file for this

 emp_angular:
  path: /voters-angular
  defaults: { _controller: "Bundle:Voters:voters_angular" }

 angular:
  path: /angular
  defaults: { _controller: "Bundle:Voters:angular" }

Refactored controller

  public function voters_angularAction(Request $request)
{
    $names = array();


    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('Bundle:City')->createQueryBuilder('c')
       ->orderBy('c.name', 'ASC')
       ->getQuery()
       ->getResult();

    foreach ($entities as $entity)
    {
        $names[] = $entity->getName();
    }

    $response = new JsonResponse();
    $response->setData($names);

    return $response;
}

public function angularAction(Request $request)
{
    return $this->render('Bundle:Voters:data.html.twig');
}

in twig

 // names // 

successfully displaying data

 ["Aborlan ","Abra de Ilog ","Abucay ","Abulug ","Abuyog ","Adams"]

how to convert this to string?

But ng-repeat directive doesnt work here

<tr ng-repeat="x in names">
<td>//x.id//</td>
<td>//x.name//</td>
</tr>

What's the possible fix for this?Is there's something wrong with the symfony controller itself?

解决方案

Your code almost working.The reason for the ng-repeat directive not working is

<tr ng-repeat="x in names">
    <td>//x.name//</td> 
</tr>

because in your symfony controller, you already loop your result, so instead use

 <tr ng-repeat="x in names">
     <td>//x//</td> 
 </tr>

Lets refactor your angular controller

<script>
    var app = angular.module('myApp', []);

    app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
    });

    app.controller('customersCtrl', function($scope, $http) {
        //$http.get("http://localhost:8093/voters/voters_angular")
        $http.get("{{ path('emp_angular') }}")
        .success(function (response) {$scope.names = response;});
    });
    //console.log(names);
</script>   

And now your view

{% block body -%}

<div ng-app="myApp" ng-controller="customersCtrl">

 <table ng-model="names" class="table">
  <thead>
    <tr>
        <th>Full Name</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="x in names track by $index">
        <td>//x//</td> 
    </tr>
  </tbody> 
 </table>
</div>  
{% endblock %}

You may wonder why in your ng-repeat directive I change your code to

  <tr ng-repeat="x in names track by $index">
        <td>//x//</td> 
  </tr>

Well you mentioned earlier that you are expecting tons of data, and it maybe possible for duplicates, so so prevent that error,

 track by $index

is added as described here

link

这篇关于搜索过滤器 - Twig 循环内的 Angular Js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆