Я новичок в Angularjs, я создал простое веб-приложение, которое берет детали у пользователя и отображает детали в представлении. Я столкнулся с проблемой при вызове метода одного контроллера с другого углового взгляда. Может кто-нибудь мне помочь, спасибо.
<div id="main">
<div id="first">
<form ng-controller="homeController as model" ng-submit="push();">
<h1>Vehicle Form</h1>
<h4>Please fill all entries.</h4>
<br>
<label>Model :</label>
<input name="dname" placeholder="Enter Model" type="text" ng-model="model.user.model">
<br>
<label>Name :</label>
<input name="demail" placeholder="Enter name" type="text" ng-model="model.user.name">
<br>
<label>Color :</label>
<input name="demail" placeholder="Enter color" type="text" ng-model="model.user.color">
<br>
<label>Price :</label>
<input name="demail" placeholder="Your Email" type="text"ng- model="model.user.price">
<br>
<input name="dsubmit" type="submit" value="Send">
</form>
</div>
</div>
<br>
<br>
<h1>Vehicle Table </h1>
<table class="table table-striped table-hover table-users" ng-controller="homeController">
<thead>
<tr>
<th>Id</th>
<th>Model</th>
<th>Name</th>
<th>Color</th>
<th>Price</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="vehicle in hello">
<td>{{vehicle.id}}</td>
<td>{{vehicle.model}}</td>
<td>{{vehicle.name}}</td>
<td>{{vehicle.color}}</td>
<td>{{vehicle.price}}</td>
<td><a class="btn mini blue-stripe" ui-sref="about" ng-click="setValue(vehicle.id)">Edit</a></td>
<td><a href="#" class="confirm-delete btn mini red-stripe" role="button">Delete</a></td>
</tr>
</tbody>
</table>
var myapp = angular.module('demo').controller("homeController", function($scope,myService){
myService.async().then(function(d){
$scope.hello=d.data;
});
var model=this;
model.user={
id:"",
model:"",
name:"",
color:"",
price:""
};
$scope.push = function(){
myService.saveUser(model.user);
model.user='';
}
});
<div id="main">
<div id="first">
<form ng-controller="aboutController" ng-submit="addValue();">
<h1>Vehicle Edit Form</h1>
<br>
<label>Id :</label>
<input name="id" placeholder="Enter Id" type="text" ng-model="id" value="value.id">
<br>
<label>Model :</label>
<input name="model" placeholder="Enter Model" type="text" ng-model="model" value="value.model">
<br>
<label>Name :</label>
<input name="name" placeholder="Enter name" type="text" ng-model="name" value="value.name">
<br>
<label>Color :</label>
<input name="color" placeholder="Enter color" type="text" ng-model="color" value="value.color">
<br>
<label>Price :</label>
<input name="price" placeholder="Your Email" type="text" ng-model="price" value="value.price">
<br>
<input name="update" type="Update" value="Send">
</form>
</div>
</div>
angular.module('demo').controller("aboutController", function($scope, aboutService) {
$scope.value;
$scope.setValue = function() {
aboutService.getVehicle().success(function (response) {
$scope.value = studs.data;
})
};
$scope.addValue = function () {
var stud = {
id:"$scope.id",
model:"$scope.model",
name:"$scope.name",
color:"$scope.color",
price:"$scope.price"
};
aboutService.setVehicle(stud).
success( function (){
concole.log("hello");
})
};
});
var myapp = angular
.module('demo', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'Views/home.html',
controller: 'homeController'
})
.state('about', {
url: '/about',
templateUrl: 'Views/about.html',
controller: 'aboutController'
})
.state('contact', {
url: '/contact',
templateUrl: 'Views/contact.html',
controller: 'contactController'
});
});
myapp.factory('myService',function($http){
var myService={
async : function(){
var promise= $http.get('http://192.168.50.127:8080/SpringRestfulVehicleDemo2/vehicle/all').then(function(response){
return response;
});
return promise;
},
saveUser : function(userArray){
$http.post('http://192.168.50.127:8080/SpringRestfulVehicleDemo2/vehicle/add ',userArray).success(
function(userArray,status,headers,config){
});
}
};
return myService;
});
myapp.factory('aboutService',function($http){
var aboutService={};
var urlBase='http://192.168.50.127:8080/SpringRestfulVehicleDemo2/vehicle/';
aboutService.getVehicle = function () {
retun $http.get(urlBase+'/byId/:id');
};
aboutService.setVehicle= function (){
return $http.post(urlBase+'/update/:id');
}
return aboutService;
});
То, что я делаю, это получение данных с сервера и отображение данных в таблице. Я хочу отредактировать выбранную строку в другом представлении. Я столкнулся с проблемой, когда я нажимаю кнопку редактирования в home.html
. Он должен вызывать about.js
(controller) setValue()
.
Для этого вам необходимо, чтобы ваши контроллеры обменивались данными друг с другом. Связь может произойти с использованием любого из следующих методов
В вашем случае вы можете переместить метод setValue на общую службу между используемыми контроллерами или вы можете использовать метод 1.
Вы уже знаете, как сделать услугу. Пример метода 1 приведен ниже:
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);
$broadcast
или$emit
если вам действительно нужно взаимодействовать между представлениями, но вы описываете простое представление master / details, которое не должно в этом нуждаться.