如何将数据传递到ng-include控制器? [英] How to pass data to a ng-include controller?
问题描述
我有一个ng-include
html元素,并希望将一些数据从外部传递到控制器.
I have an ng-include
html element, and want to pass some data from outside to the controller.
http webservice
中的主controller
fetches
json
data
,并将数据提取到范围变量climadata
中.
The main controller
fetches
json
data
from a http webservice
, and extracts the data into the scoped variable climadata
.
以下是pseudocode
,但您知道了:
function mainController($scope, $http) {
$http.get().then(
$scope.climadata = response.clima;
);
}
<div ng-controller="mainController">
<div ng-include="'clima.html'" ng-controller="climaController" onload="climamodel = climadata"></div>
</div>
这很好,但是climadata永远不会到达climaController
.检查如下:
This works fine, BUT the climadata never reaches the climaController
. Checked as follows:
function climateController($scope) {
console.log($scope.climamodel); //prints "undefinied"
};
climamodel在控制台中始终是未定义的,但是为什么呢?
The climamodel is always undefined in console, but why?
推荐答案
这是可行的,获得undefined
的原因是因为您是通过$http
请求获得数据的,因此,在获得数据climaController
将执行,此时将没有范围变量调用climadata
.
This is working, the reason you getting the undefined
is because, you get the data by $http
request, because of that, before you get the data climaController
will execute, at that point there is no scope variable call climadata
.
检查此演示
您可以看到控制台正在打印undefined
,但是在ajax请求后数据可用后,您将在部分HTML
页面上获取数据.
you can see the console is printing undefined
but you will get the data on partial HTML
page after the data is available after ajax request.
如果要在ajax完成后加载inclcude
,请使用ng-if
If you want to load the inclcude
after the ajax is complete then use ng-if
<div ng-if="climadata" ng-include="'clima.html'" ng-controller="climaController"></div>
如果存在climadata
,则仅此div进程表示include
仅在climadata
可用时起作用.
if climadata
is present then only this div process that means include
works only if climadata
is available.
,您可以从onload="climamodel = climadata"
这篇关于如何将数据传递到ng-include控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!