无法正确获取作用域变量

Can not get the scope variable properly

我有一个简单的文本框和一个按钮,每当用户单击按钮时,警报都会显示文本框的文本,但我想这样做(我知道有很多更好的方法,但首先我想了解为什么这种方式行不通):

var app = angular.module('app', []);
app.factory('Service', function() {
    var service = {
            add: add
        };
        return service;
        function add($scope) {
            alert($scope.user.username);
        }
});
app.controller('table', function(Service,$scope) {
    //get the return data from getData funtion in factory
    this.add = Service.add($scope);

});

如您所见,我将示波器发送到工厂,然后将 user.username 定义如下:

    <button class="btn btn-primary" ng-click="t.add(user.userName)">

但是当我 运行 这没有任何反应 谁能告诉我这段代码有什么问题吗?

<body ng-app="app">
<form>
    <div class="row commonRow" ng-controller="table as t">
        <div class="col-xs-1 text-right">item:</div>
        <div class="col-lg-6 text-right">
            <input id="txt" type="text" style="width: 100%;"
                ng-model="user.userName">
        </div>

        <div class="col-xs-2">
            <button class="btn btn-primary" ng-click="t.add(user.userName)">
                click me</button>
        </div>
    </div>
</form>

plnk link 如下:

plnkr

第一件事是你不能在控制器中的 service.and 中使用 $scope 你不能将 this(object) 赋给 $scope.so $scope 不包含任何值。 我想你会这样写 $scope.user = 这个;

问题出在这一行

this.add = Service.add($scope);

在这里,您将 Service.add($scope) 调用的返回值(即 undefined)分配给 this.add

正确的方法是

this.add = function(data) { Service.add($scope); }

this.add = Service.add;

// in the service factory.
function add(usrNm) {
    alert(usrNm);
}