我有一个SPA,有两个不同的视图,一个用于主题,一个用于学生, 在主题视图中,我在app / views / subject / subject.html中有一个保存按钮:
<button type="button" class="btn btn-warning" ng-click="saveInfo()">
Save
</button>
我想在学生视图中添加相同的功能,saveInfo()将数据传递到app工厂中的服务,该服务通过fill_table.php将数据保存在DB中。 app / javascript / services.js中的app工厂:
var app = angular.module('myApp');
app.factory("services", ['$http', function($http) {
var serviceBase = 'http://localhost/php/';
var obj = {};
document.title = "myApp on " + serviceBase;
obj.postData = function (user, data) {
return $http.post(serviceBase + 'fill_table.php', { "data": data, "user": {'username': user.name, 'password': user.password }).then(function (results) {
return results.data;
});
};
saveInfo()位于app / views / subject / subject.js:
$scope.saveInfo = function() {
console.log("saveInfo");
$scope.loadingInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modalLoading.html',
size: "l",
});
return getChanges( $indexedDB, $q).then( function(responsesArray) {
var jsonData = {};
$scope.errorInstance = undefined;
for (var i=0; i < DB_TABLES.length; i++) {
var table = DB_TABLES[i];
var items = responsesArray[i]
if (items.length > 0){
jsonData[table] = items;
}
}
console.log(JSON.stringify(jsonData));
return services.postData($scope.selectedUser, jsonData);
})
}
我想将提到的按钮添加到app / views / student / student.html中。我尝试并将subject.js中的代码复制到学生中,但由于某种原因它不起作用,虽然我检查了一切都是正确的,所以有没有办法只将该功能从subject.js转移到Student.html
note 1 getChanges()是另一个函数获取插入的信息并将其传递给saveinfo()。
note 2 现在我可以通过在主题视图中按保存按钮来保存信息插入的学生视图
答案 0 :(得分:0)
如果我理解正确,你有两个html文件和两个控制器(学生和主题)。要在这些之间共享数据/功能,您可以使用服务或工厂来处理所有http请求。这是可重复使用的,可从所有控制器访问。
app.factory("services", ['$http', function($http) {
var postStudent = function (student) {
return $http.post("api/Student/Post", student);
};
var getChanges = function (){
return $http.get("api/Student/Changes", student);
};
return {
postStudent : postStudent,
getChanges : getChanges
};
}])
现在您可以使用可以根据需要调用控制器中的服务。
app.controller('StudentController', ['service', function(service){
service.postStudent(student).then(function successCallback(response) {
console.log('success');
}, function errorCallback(response) {
console.log('error ' + response);
});
service.getChanges().then(function successCallback(response) {
console.log('success');
}, function errorCallback(response) {
console.log('error ' + response);
});
}]);
app.controller('SubjectController', ['service', function(service){
service.postStudent(student).then(functionsuccessCallback(response){
},
function errorCallback(response) {
});
service.getChanges().then(function successCallback(response) {
},
function errorCallback(response) {
});
}]);
请注意,上述内容尚未实施,但应为您提供大纲。