gpt4 book ai didi

javascript - Angular - 将 ng-init 从 View 传输到 Controller

转载 作者:行者123 更新时间:2023-11-28 05:47:08 25 4
gpt4 key购买 nike

我对 ng-init 的看法是这样的:

                    <div class="map-content" style="min-height: 200px">
<div ng-init="data = {latitude : 35.757563, longitude: 51.409469}">
<div map-marker ng-model="data" class="demo-map"></div>
</div>
</div>

这是我的 Controller :

app.controller('mapController' , function($scope) {})
.directive('mapMarker',function(){
return {
restrict: 'EA',
require: '?ngModel',
scope:{
myModel: '=ngModel'
},
link: function(scope , element, attrs , ngModel) {

scope.mapData = {};
scope.mapData.latitude = attrs.latitude;
scope.mapData.longitude = attrs.longitude;
console.debug(scope.myModel);
var mapOptions;
var googleMap;
var searchMarker;
var searchLatLng;

ngModel.$render = function(){
searchLatLng = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);

mapOptions = {
center: searchLatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

googleMap = new google.maps.Map(element[0],mapOptions);

searchMarker = new google.maps.Marker({
position: searchLatLng,
map: googleMap,
draggable: true
});

google.maps.event.addListener(searchMarker, 'dragend', function(){
scope.$apply(function(){
scope.myModel.latitude = searchMarker.getPosition().lat();
scope.myModel.longitude = searchMarker.getPosition().lng();
});
}.bind(this));

};

scope.$watch('myModel', function(value){
var myPosition = new google.maps.LatLng(scope.myModel.latitude, scope.myModel.longitude);
searchMarker.setPosition(myPosition);
}, true);
}
}
});

我想将 ng-init 传输到我的 Controller 中。你对此有什么想法吗?

最佳答案

很简单:

app
.controller('mapController', function($scope) {
$scope.data = {
latitude: 35.757563,
longitude: 51.409469
};
})
.directive('mapMarker', function() {
// ...
});

当然还要从 HTML 中删除它:

<div class="map-content" style="min-height: 200px">
<div map-marker ng-model="data" class="demo-map"></div>
</div>

关于javascript - Angular - 将 ng-init 从 View 传输到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38409799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com