kin*_*inx 6 javascript angularjs
我在提交表单后尝试将新行数据推送到表中.但是,调用的表UrlListCtrl
与表单不同,即UrlFormCtrl.
function UrlFormCtrl($scope, $timeout, UrlService) {
$scope.message = '';
var token = '';
$scope.submitUrl = function(formUrls) {
console.log('Submitting url', formUrls);
if (formUrls !== undefined) {
UrlService.addUrl(formUrls).then(function(response){
$scope.message = 'Created!';
// I need to update the view from here
});
} else {
$scope.message = 'The fields were empty!';
}
}
Run Code Online (Sandbox Code Playgroud)
在UrlFormCtrl
,我发送一个数组到数据库进行存储,之后我想更新视图,在哪里UrlListCtrl
处理它.
function UrlListCtrl($scope, $timeout, UrlService){
UrlService.getUrls().then(function(response){
$scope.urls = response.data;
});
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将新数据推送到$scope.url
.这是服务:
function UrlService($http) {
return {
addUrl: addUrl,
getUrls: getUrls
}
function addUrl(formUrls) {
console.log('adding url...');
return $http.post('urls/create', {
original_url: formUrls.originalUrl,
redirect_url: formUrls.redirectUrl
});
}
function getUrls() {
return $http.get('urls/get');
}
}
Run Code Online (Sandbox Code Playgroud)
我还在尝试理解Angular,所以这对我来说非常复杂.如何$scope.urls
从内部更新UrlFormCtrl
?
我不确定我是否完全理解你的问题,但无论如何我都会尝试回答它=)。
那么您正在尝试更新其值在另一个控制器中已更改的变量?
那就是哪里service
有用的地方。
以下是基本步骤:
在服务中,您有该变量:
myApp.service('ServiceName', ['$http', function(){
var urls = [];
return{
urls: urls
}
}])
Run Code Online (Sandbox Code Playgroud)
放入$watch
一个控制器,您想在其中获取新值:
myApp.controller('FirstController', function(...){
$scope.$watch(function () {
return ServiceName.urls;
}, function (newVal) {
$scope.urls = newVal;
});
})
Run Code Online (Sandbox Code Playgroud)
然后,您从另一个控制器更改它:
myApp.controller('SecondController', function(...){
ServiceName.urls.push('newValue');
})
Run Code Online (Sandbox Code Playgroud)
这应该可以做到。$scope.urls
即使在第二个控制器中发生更改,也会在第一个控制器中更新。
的概念$watch
对您来说可能是新的。因此,每当第一个函数返回新值时,它基本上都会执行回调函数。也就是说,每当被监视的变量发生变化时。
在你的情况下:
您的服务中将有一个变量:
function UrlService($http) {
var urls = [];
function addUrl(formUrls) {
console.log('adding url...');
return $http.post('urls/create', {
original_url: formUrls.originalUrl,
redirect_url: formUrls.redirectUrl
});
}
function getUrls() {
return $http.get('urls/get');
}
return {
addUrl: addUrl,
getUrls: getUrls
urls: urls
}
}
Run Code Online (Sandbox Code Playgroud)
$watch
里面放一个UrlListCtrl
:
function UrlListCtrl($scope, $timeout, UrlService){
$scope.$watch(function () {
return UrlService.urls;
}, function (newVal) {
$scope.urls = newVal;
});
}
Run Code Online (Sandbox Code Playgroud)
urls
然后,更改from的值UrlFormCtrl
:
$scope.submitUrl = function(formUrls) {
if (formUrls !== undefined) {
UrlService.addUrl(formUrls).then(function(response){
$scope.message = 'Created!';
UrlService.urls = response['urls'];
});
} else {
$scope.message = 'The fields were empty!';
}
}
Run Code Online (Sandbox Code Playgroud)
您$watch
放入 insideUrlListCtrl
将确保新值将分配给$scope.urls
inside UrlFormCtrl
。
归档时间: |
|
查看次数: |
79 次 |
最近记录: |