ng-model在ui-router嵌套视图中不起作用

时间:2017-05-09 23:51:30

标签: angularjs angular-ui-router

我有以下代码结构

的index.html

<body ng-app="jobPortalApp" ng-controller="mainController">
   <div ui-view></div>
</body>

然后是我的homepage.html模板

<div id=header>
</div>
<div ui-view>
     <input type="text" ng-model="test">Test</input>
     <input type="submit" ng-click="signup()">
</div>
<footer>
</footer>

我的角度模块文件如下

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

jobPortalApp.config(function($stateProvider, $urlRouterProvider){

    $urlRouterProvider
        .otherwise('/');

    $stateProvider
        .state('home',
            {
                url:'/',
                templateUrl: './templates/homepage.html',
                controller: 'controllerHome'
            })
}).controller('mainController', function(){});

以下是我的家庭控制器

jobPortalApp.controller('controllerHome',function($scope, $http) {
     $scope.test="";
     $scope.signup = function() {
         console.log($scope.test);
     }
});

必需: 在用户点击注册

后,我想在我的controllerHome中更改test的值

问题:

console.log输出空白,如果我删除$scope.test="";,则输出undefined。我希望在我的控制器中更改test的值。

1 个答案:

答案 0 :(得分:2)

由于原型继承问题,您通常不应该直接绑定到$scope。尝试从子范围读取值时,如果该值不存在,则最终从父范围读取。但是一旦你写,你就写信给孩子范围。如果你绑定到一个对象呢?

$scope.data = {
    test: ""
};

<input type="text" ng-model="data.test">Test</input>

作为替代方案,您可能还需要查看路线的controllerAs选项:

controllerAs: "ctrl"

然后在你的控制器中:

this.test = "";

在你的模板中:

<input type="text" ng-model="ctrl.test">Test</input>