在我的控制器中,我有一个$ http调用,它返回一个json字符串,然后我想传递给一个指令添加到地图中。字符串从控制器传递到指令罚款,但不是从控制器内的$ http函数传递到指令。
wmm.controller('wapMapClr', ['$rootScope', '$scope', '$window', '$http', function ($rootScope, $scope, $window, $http) {
$scope.geobj = {};
$scope.geobj.geoprop = ""
// Search by postcode
// create a blank object to hold our form information
$scope.formData = {};
$scope.pcSearch = function () {
$scope.data = {};
$http.post('api/api.php', { postcode: $scope.formData } )
.success(function (result) {
$scope.geobj = {geoprop : result.json_string};
console.log($scope.geobj.geoprop);
任何帮助都会非常感激。感谢
答案 0 :(得分:1)
Promises
是异步的,因此您不知道promise
何时返回,因此无法立即为您提供
您的指令采用controller
方法,您可以从中触发可以访问的$http
来电。
您可以使用$emit/$brodcast
收听从controller
传递到指令的事件。
我不确定你得到了什么错误,这里有$timeout
使用的async
小提琴,它有效。{/ p>
var myApp = angular.module('myApp',[]);
myApp.directive('passObject', function() {
return {
restrict: 'E',
scope: { obj: '=' },
template: '<div>Hello, {{obj.prop}}!</div>'
};
});
myApp.controller('MyCtrl', function ($scope, $timeout) {
$scope.obj = { prop: "world" };
$timeout(function(){
$scope.obj = { prop: "from timeout" };
},10000);
});
答案 1 :(得分:0)
谢谢Thalaivar。我修改了你给的代码并且它有效。见下文:
wmm.controller('wapMapClr', ['$scope', '$window', '$http', function ($scope, $window, $http) {
$scope.geobj = {};
// Search by postcode
// create a blank object to hold our form information
$scope.formData = {};
$scope.pcSearch = function () {
$scope.data = {};
$http.post('api/api.php', { postcode: $scope.formData } )
.success(function (result) {
$scope.geobj = {geoprop : result.json_string};
然后在指令......
wmm.directive('tchOlMap', function () {
var MAP_DOM_ELEMENT_ID = 'tchMap';
return {
restrict: 'E',
//BELOW IS THE LINE I CHANGED TO MAKE IT WORK!
scope: false,
replace: true,
template: '<div id="' + MAP_DOM_ELEMENT_ID + '" class="full-height"></div>',
link: function postLink(scope, element, attrs) {