ayu*_*hgp 5 javascript angularjs
是否可以从控制器外部设置控制器的$ scope变量?
例如,如果我有一个控制器:
app.controller('citySelectCtrl', ['$scope',function($scope){
}]);
Run Code Online (Sandbox Code Playgroud)
以及具有事件处理程序的全局范围中的函数.现在我想$scope在事件发生时设置一个变量.可能吗?我的全球职能:
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{
componentRestrictions: {'country': 'in'},
types: ['(cities)']
});
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 22.5937, lng: 78.9629},
zoom: 5,
minZoom: 5
});
}
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
----------------------------------------------------------
//SET $scope.city = place here
----------------------------------------------------------
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
Run Code Online (Sandbox Code Playgroud)
我们可以用于$injector访问范围之外的 Angular 服务。以你为例。
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
----------------------------------------------------------
var elem = angular.element(document.querySelector('[ng-app]'));
var injector = elem.injector();
var $rootScope = injector.get('$rootScope');
$rootScope.$apply(function(){
$rootScope.city = place //or city;
});
----------------------------------------------------------
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
Run Code Online (Sandbox Code Playgroud)
在你的控制器中你可以使用。
app.controller('citySelectCtrl', ['$scope','$rootScope',
function ($scope,$rootScope) {
$rootScope.city = {};
}
]);
Run Code Online (Sandbox Code Playgroud)
欲了解更多详情请查看此
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
4242 次 |
| 最近记录: |