【问题标题】:Angular $scope not working inside modal windowAngular $scope 在模态窗口中不起作用
【发布时间】:2015-06-06 10:40:46
【问题描述】:

我正在关注 this guide 以在我的 Angular 应用程序中实施身份验证,但我无法访问控制器内的模型。

在我的应用程序的某个地方,我像这样打开模态窗口:

loginModal().then(function() {
    // Successful login, proceed to the page the user wants
    return $state.go(toState.name, toParams);
}).catch(function() {
    // Login failed, return home
    return $state.go('home');
});

loginModal() 是一个服务,看起来像这样:

myApp.service('loginModal', function($modal, $localStorage) {
    function assignCurrentUser(user) {
        $localStorage.user = user;
        return user;
    }

    return function() {
        var instance = $modal.open({
            templateUrl: '/partials/modals/login.html',
            controller: 'LoginController',
            windowClass: 'small'
        });

        return instance.result.then(assignCurrentUser);
    };
});

当使用loginModal() 服务时,它会在包含/partials/modals/login.html 文件的HTML 的页面上打开一个模式窗口。这一切都完美无缺。您会注意到我还指定了要在模式中使用的控制器:LoginController

LoginController 是这样写的:

myApp.controller('LoginController', function($scope) {
    $scope.login = function() {
        console.log($scope.user);
    };
});

最后是模态窗口中使用的部分:

<form name="loginForm" novalidate method="post" ng-submit="login();">
    <label>Email address
        <input type="email" name="email" ng-model="user.email">
    </label>
    <label>Password
        <input type="password" name="password" ng-model="user.password">
    </label>
    <input type="submit" value="Login">
</form>

问题是,当我填写表单(通过填充 user.emailuser.password)并单击提交按钮时,我将 undefined 打印到控制台。

基本上,我的LoginController 中的$scope.login 函数确实会执行,但是$scope.user 属性是未定义的,即使它应该由模式窗口中的表单填充(使用ng-models) .

另外,如果我将{{user.email}} 放入模态模板,然后填充电子邮件字段,它确实会被打印出来。所以我知道双向数据绑定有效。

为什么我不能从控制器内的模式窗口访问 $scope 值?

【问题讨论】:

  • 这个问题解决了吗,还是你还需要什么?

标签: javascript angularjs scope modal-dialog


【解决方案1】:

如果有帮助,现在不要这样做,但我在路由方面遇到了这样的问题。 解决方案是使用ng-model="$parent.user.name"$parent 添加到控制器的依赖项列表中,并使用$scope.$parent.user.email 调用它 或者只是$scope.user.email有时它有效。 希望对你有所帮助。

【讨论】:

  • 不,这些都不起作用:(虽然我认为你可能已经把我推向了正确的方向来解决这个问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
相关资源
最近更新 更多