使用Angular UI模态框时的作用域问题
使用Angular UI模态框时的作用域问题
我在理解和使用angular UI模态框的作用域时遇到了问题。
虽然在这里不是立即显而易见的,但我已经正确设置了模块和一切(据我所知),但特别是这些代码示例是我找到错误的地方。
index.html(其中重要的部分)
Controller.js(同样,重要的部分)
MyApp.controller('AppListCtrl', function($scope, $modal){ $scope.name = '新名称'; $scope.groupType = '新类型'; $scope.open = function(){ var modalInstance = $modal.open({ templateUrl: 'partials/create.html', controller: 'AppCreateCtrl' }); modalInstance.result.then(function(response){ // 输出一个对象{name: '自定义名称', groupType: '自定义类型'} // 尽管用户输入了定制的值 console.log('response', response); // 输出"新名称",这很好,对我来说是有意义的。 console.log('name', $scope.name); }); }; }); MyApp.controller('AppCreateCtrl', function($scope, $modalInstance){ $scope.name = '自定义名称'; $scope.groupType = '自定义类型'; $scope.ok = function(){ // 输出'自定义名称',尽管用户输入了"TEST 1" console.log('create name', $scope.name); // 输出'自定义类型',尽管用户输入了"TEST 2" console.log('create type', $scope.groupType); // 输出AppCreateCtrl的$scope,但name和groupType仍显示为"自定义名称"和"自定义类型" // $scope.$id是"007" console.log('scope', $scope); // 输出看起来像作用域的对象,但在此对象中,name和groupType的值为"TEST 1"和"TEST 2",如预期。 // this.$id设置为"009",所以this!=$scope console.log('this', this); // 根据modalInstance.result.then()的说法, // 此对象中的值是最初的$scope值,而不是用户刚刚在UI中输入的值。没有数据绑定? $modalInstance.close({ name: $scope.name, groupType: $scope.groupType }); }; });
create.html(完整内容)
添加模板组
所以,我的问题是:为什么作用域没有被双向绑定到UI?为什么this
有定制的值,但$scope
没有?
我尝试在create.html的body div中添加ng-controller="AppCreateCtrl"
,但出现错误:"Unknown provider: $modalInstanceProvider <- $modalInstance",所以没有帮助。
在这一点上,我的唯一选择是使用this.name
和this.groupType
返回一个对象,而不是使用$scope
,但这感觉不对。