我使用自动完成字段,需要根据php(YII2)操作从mysql数据库中列出数据。目前,自动填充字段已静态填充。 用于填充自动填充字段的代码如下所示。
app.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($timeout, $q) {
var self = this;
// list of `state` value/display objects
self.states = loadAll();
self.selectedItem = null;
self.searchText = null;
self.querySearch = querySearch;
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function querySearch(query) {
var results = query ? self.states.filter(createFilterFor(query)) : self.states;
var deferred = $q.defer();
$timeout(function () {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
}
/**
* Build `states` list of key/value pairs
*/
function loadAll() {
var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
Wisconsin, Wyoming';
return allStates.split(/, +/g).map(function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
}
这里在函数loadall()中,我需要从我的数据库获取值,这是从我的YII2控制器操作返回的。它可以通过url加入我的控制器操作如下所示
public function actionGetAllPackages()
{
$packages = \common\models\Packages::find()
->select('name')
->all();
$name = "";
foreach ($packages as $package)
{
$name = $name.', '.$package->name;
}
$name = substr($name, 2);
echo addslashes($name);
}
如何将控制器动作打印的值带到角度函数?请帮忙 。我第一次使用YII2和角度。
提前致谢
答案 0 :(得分:1)
只需在脚本中的GetAllPackages()
方法中向控制器中的loadAll()
函数调用$ http请求,并将该值分配给allstates
。