好的,第一个问题所以......友善一点......
我正在使用 Angular 的 Material 框架制作这个 Angular 自动填充输入。
我需要用来自 ajax 调用的数据填充它。 (即国家数组) 我最初的方法是将模块注入(inject)应用程序的 Controller 中,然后当 ajax 调用返回成功时,我将触发它的函数。
这效果不佳,因为它在数据返回之前加载一次(从注入(inject))并在检查时崩溃。
采取两个措施:添加对空数据的检查会导致其按预期加载和停止,然后当数据到来(最终)时,模块将它们切成单独的项目并准备就绪,但页面无法工作。我所说的“不会工作”是指它不会在您键入时自动建议..
我认为我需要加载模块而不是其中的函数,但我似乎无法做到这一点..这就是我需要帮助的..
添加代码:
angular.module("Myapp", ['ngMaterial', 'Autofill-country' ])
.controller("mycontroller", ["$scope", "$http", function ($scope, $http) {
//automatic suggest
automaticsuggest ()
function automaticsuggest() {
suggesturl = 'http://www.mysuggest_front_services'
$http({
method: 'GET',
url: suggesturl,
responseType: "json",
async: false // Just tried that to see if it works.. I am not really fond of it
}).then(function (response) {
countriesarrey = response.data.Countries
// .run('Autofill-country', ['Autofill-country']) - Tried this too..
country(); // this is the function of the autosuggest.
Once checked with breakpoints it does get the array and cut it and filter it etc, but the n when you input something in the input field.. It doesnt suggest..
});
}
以及自动完成模块
angular.module('Autofill-country', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('country', country);
function country($timeout, $q) {
var self = this;
if (countriesarrey == "undefined" || countriesarrey == null) { }
else { countrys(); }
// list of `country` value/display objects
function countrys() {
self.countries = loadAll();
self.selectedItem = null;
self.searchTextcountry = null;
self.querySearch = querySearch;
// ******************************
// Internal methods
// ******************************
/**
* Search for countries... use $timeout to simulate
* remote dataservice call.
*/
function querySearch(query) {
var results = query ? self.countries.filter(createFilterFor(query)) : [];
return results;
}
/**
* Build `countries` list of key/value pairs
*/
function loadAll() {
var allcountries = countriesarrey;
console.log(countriesarrey);
return allcountries.split(/, +/g).map(function (country) {
return {
value: country.toLowerCase(),
display: country
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(country) {
return (country.value.indexOf(lowercaseQuery) === 0);
};
}
}
}
最佳答案
你应该创建一些工厂来获取你的数据,它将有一个方法,返回 promise 。 Promise 解决后,您可以使用获取的数据执行您想要的操作。
var myApp = angular.module('myApp', []);
myApp.factory('myFactory', function($http, $q, $timeout) {
return {
getData: function() {
// return $http.get(...);
},
};
});
myApp.controller('MyCtrl', function(myFactory) {
this.getData = function() {
myFactory.getData().then(function(response) {
// use response.data here
})
}
})
参见 fiddle :http://jsfiddle.net/jcpmsuxj/44/
关于javascript - Angular 在函数启动后注入(inject)模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724780/