简体   繁体   English

为什么$ scope没有传递给控制器​​?

[英]Why is $scope not getting passed to controller?

For some reason $scope.username is not being passed to my controller. 由于某种原因,未将$scope.username传递给我的控制器。 On click registerUser() $scope.username is undefined. 单击时, registerUser() $scope.username未定义。 I do have a scope and the function is running just no $scope.username. 我确实有一个作用域,并且该函数仅运行$ scope.username。

For example: 例如:

HTML: HTML:

 <input bs-form-control
     type="text"
     ng-model="username"
     label="Username"
     />

<button class="btn btn-primary" ng-click="registerUser()">Register</button>

controller: 控制器:

    .controller("loginController", ['$scope',
        function ($scope) {
            $scope.registerUser = function(){
                console.log($scope.username) // <=== undefined!
            }

  }])

My controller is passed using state: 我的控制器使用状态传递:

.state('register', {
            url: "/register",
            templateUrl: "/static/html/profile/register.html",
            controller: "loginController"
        })

I think bs-form-control creates a new isolated scope. 我认为bs-form-control创建了一个新的隔离范围。 What you should do is either use objects on your scope ( Does my ng-model really need to have a dot to avoid child $scope problems? ) or use the new "constroller as" syntax introducted in AngularJS 1.2. 您应该做的是使用范围内的对象( 我的ng模型是否真的需要一个点来避免子级$ scope问题? )或使用AngularJS 1.2中引入的新“ constroller as”语法。 It works with ui-router too! 它也适用于ui-router!

See this plunker: http://plnkr.co/edit/hkmMGbTtURSHDH84miiK?p=preview 看到这个矮人: http ://plnkr.co/edit/hkmMGbTtURSHDH84miiK?p=preview

Routing: 路由:

.state('register', {
    url: "/register",
    templateUrl: "/static/html/profile/register.html",
    controller: "loginController as loginCtrl"
})

Template: 模板:

<input bs-form-control type="text" ng-model="loginCtrl.username" label="Username" />
<button class="btn btn-primary" ng-click="loginCtrl.registerUser()">Register</button>

Controller: 控制器:

Use this instead of $scope : 使用this代替$scope

.controller("loginController", [
    function () {
        this.registerUser = function(){
            console.log(this.username);
        }
    }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM