Angular JS:如何使Ajax调用指令来创建选项 [英] Angular js : How to make make ajax call for directives to create options

查看:41
本文介绍了Angular JS:如何使Ajax调用指令来创建选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为表单控件创建了指令. 有一些控件会从ajax [API]调用中提供选项.

I created directives for form controls. There are some controls those will have options from ajax[API] call.

我被困在这里,如何通过指令进行Ajax调用.

I am stuck here how to make ajax call over directives.

    function selectControlDir()
    {
        return {
            transclude: true,
            restrict: 'E',
            scope: {
                data: '=data'
            },
            template: "<div ng-transclude></div><label>{{data._text}} </label><select type='text' name='{{data._attributeName}}' id='{{data._attributeName}}' >\n\
<option ng-repeat='ans in data._answerOptions'>{{ans._promptText}}</option></select>"
            ,
            link: function (scope, element, attrs)
            {
                //console.log("scope.data.QuestionData", scope.data.QuestionData);
            }
        };
    }

插入完整代码 http://plnkr.co/edit/Op1QDwUBECAosPUC7r3N?p=preview

在这里,我想进行Year的api调用(页面加载). 按年份更改更新选项.

Here I want to make api call for Year (on page load). on year change update options of Make.

推荐答案

为此,您最好做的是在year元素上有一个ng-change事件指令,并且可以在控制器中使用它来拥有一个数组包含当年发生的所有事件:

What you can do for this is better to have a ng-change event directive on the year element and in the controller you can use to have an array which holds all the make happened in that year:

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

app.controller('yourController', ['$scope', '$http',
  function($scope, $http) {
    $scope.o = {
      makes: [{make:'Make1'}, {make:'Make2'}], // <---just for demo
      getMake: function(year) {
        $http.post(url, {
            year: year  // <----pass the year to backend as year like : { year:1990 }
          })
          .then(function success(response) {
              $scope.o.makes = response.data; // <---put actual data here
            },
            function error(e) {
              console.error(e);
            });
      }
    };
  }
]);

<div ng-app='yourApp' ng-controller='yourController'>
  <select ng-model='year' ng-change='o.getMake(year)'>
    <option>1990</option>
    <option>1991</option>
  </select>
    <select ng-model='make' ng-options='make as make.make for make in o.makes track by make.make'>
    <option>Make...</option>
  </select>
</div>

这篇关于Angular JS:如何使Ajax调用指令来创建选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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