【问题标题】:Access scope binding with ui-router使用 ui-router 访问范围绑定
【发布时间】:2014-05-24 22:38:10
【问题描述】:

我的 AngularJS 应用程序中有一个登录路由和页面,带有 ui-router。 在我部分加载了 ui-view 的 login.html 中,我有一个登录页面,其中的用户名和密码输入绑定到 credentials.username 和 credentials.password。如果我想在我的 LoginCtrl 中访问这些凭据,我会收到“未定义的用户名”错误。

app.js:

var myApp = angular.module('myApp', ['ui.router']);

myApp.config(function($stateProvider, $urlRouterProvider) {
    $stateProvider.state('login', {
       url: '/login',
       templateUrl: '/partials/login.html',
       controller: 'loginCtrl'
    });
});

登录Ctrl.js:

myApp.controller('loginCtrl', function($rootScope, $scope) {
    $scope.credentials.username = 'Test';
});

在我的 partials/login.html 中,我有一个简单的登录表单,其中包含 2 个输入:

<input type='text' name='username' ng-model='credentials.username' placeholder='Username...' autoFocus>
<input type='password' name='password' ng-model='credentials.password' placeholder='Password...'>

其中 autoFocus 是用于自动聚焦用户名字段的自定义指令。表单显示正常,但我仍然无法访问控制器中的绑定。

我做错了什么?

【问题讨论】:

    标签: javascript angularjs scope angular-ui-router


    【解决方案1】:

    您收到“未定义的用户名”错误的原因是因为 $scope.credentials 未定义,并且您正在尝试为 $scope.credentials.username 分配一个值。

    让这个工作的方法是先定义它:

    $scope.credentials = {};
    $scope.credentials.username = "someDefaultUsername";
    

    绑定可以使用点很好地工作 - 事实上,这是推荐的方式,因为原型范围继承的常见错误(但这是题外话):

    <input ng-model="credentials.password" type="password">
    

    题外话:带有驼峰式大小写的指令,如autoFocus,需要在 HTML 中非规范化为连字符名称,否则 Angular 的编译器将找不到它。

    <input ng-model="credentials.username" auto-focus>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      相关资源
      最近更新 更多