有人请告诉我如何解决这个问题。在我的主文件中,我使用startEdit($ index)函数来获取必须更改的输入值,并将我重定向到/ edit partial。在这里,我在输入框中键入一个新文本,并使用save()保存新值,然后将我重定向回主视图,在那里我可以看到新文本。
问题是我没有在save()函数中获取$ rootScope.siteBox的新值; 。我得到了相同的旧值,即使在$ watch函数中我也可以看到变量正在改变。
我尝试了很多解决方案但没有结果。有人请帮忙告诉我出了什么问题。
JS FILE
angular.module('maintenance', ['ngRoute'])
.controller('siteEditCtrl', SiteEditCtrl)
.controller('mainCtrl', MainCtrl)
.controller('addCtrl', AddCtrl)
.controller('editCtrl', EditCtrl)
.controller('deteleCtrl', DeteleCtrl)
.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/lists.html',
controller: 'mainCtrl'
})
.when('/add', {
templateUrl: 'views/add.html',
controller: 'addCtrl'
})
.when('/edit', {
templateUrl: 'views/edit.html',
controller: 'editCtrl'
})
.when('/detele', {
templateUrl: 'views/detele.html',
controller: 'deteleCtrl'
})
.otherwise({
redirectTo: '/'
});
});
function SiteEditCtrl($scope, $location, $rootScope) {
$rootScope.sites = sites;
$rootScope.selected = -1;
$scope.startAdd = function() {
$location.path( "/add" );
};
$scope.startEdit = function(index) {
$rootScope.selected = index;
$rootScope.siteBox = $rootScope.sites[index];
//console.log($rootScope.siteBox);
$location.path( "/edit" );
};
}
function EditCtrl($scope, $location, $rootScope) {
$scope.$watch('siteBox', function(newValue, oldValue) {
//console.log(oldValue);
//console.log(newValue);
});
$scope.save = function() {
console.log($rootScope.siteBox);
$rootScope.sites[$rootScope.selected] = $rootScope.siteBox;
$location.path( "#/" );
};
}
config(/)
中的主视图 <div class="row">
<div class="col-sm-12">
<a class="btn btn-primary btn-lg" ng-click="startAdd()">
Add new dive
</a>
</div>
</div>
<h2>List of Dive Sites</h2>
<div class="row" ng-repeat="site in sites"
ng-class="{oddRow: $index % 2 == 0}">
<div class="col-sm-8">
<h4>{{$index + 1}}: {{site}}</h4>
</div>
<div class="col-sm-4" style="margin-top: 5px;">
<div class="pull-right">
<button class="btn btn-warning btn-sm" ng-click="startEdit($index)">
Edit
</button>
<button class="btn btn-danger btn-sm" ng-click="startRemove($index)">
Delete
</button>
</div>
</div>
</div>
在配置中修改视图(/ edit)
<h3>Edit the dive site name</h3>
<div class="row">
<div class="col-sm-6">
<input type="text" class="form-control input-lg" placeholder="site name" ng-model="siteBox">
</div>
</div>
<div class="row" style="margin-top: 12px;">
<div class="col-sm-6">
<button class="btn btn-succes btn" ng-disabled="siteBox==''" ng-click="save()">
Save
</button>
<button class="btn btn-warning btn" ng-click="cancel()">
Cancel
</button>
</div>
</div>
答案 0 :(得分:0)
要在视图之间共享变量,请考虑使用工厂/服务。您可以在工厂中存储站点,并在必要时更新/检索。
答案 1 :(得分:0)
这是违反ng-model "dot rule"的经典案例。
实际上,通过在标记中添加ng-model="siteBox"
,当输入值发生更改时,siteBox
的作用域上的editCtrl
属性设置为,而不是正如您所期望的那样$rootScope
。
相反,在控制器代码中使用$rootScope.data.siteBox
,在视图代码中使用data.siteBox
而不是$rootScope.siteBox
/ siteBox
,以便在正确的对象上设置属性。确保尽早将$rootScope.data
初始化为空对象。