angularjs和调用函数在同一个对象中

时间:2014-11-29 09:00:20

标签: angularjs

我使用两个带有angularjs的简单形式

<form ng-controller="ctrs.ctr1">
    <input type="text" placeholder="Name" ng-model="name" />{{getName()}}
</form>

<form ng-controller="ctrs.ctr2">
    <input type="text" placeholder="Name" ng-model="name" />{{getName()}}
</form>

和s小脚本,例如显示名称两次

var ctrs = {
    nameTwoTimes: function(name) {
        return name+" "+name;
    },
    ctr1: function($scope, $timeout) {
        $scope.name = '';
        $scope.getName = function() {
            return $scope.name+" "+$scope.name;
        };
    },
    ctr2: function($scope, $timeout) {
        $scope.name = '';
        $scope.getName = function() {
            this.nameTwoTimes($scope.name);
        };
    }
};

如何使用函数nameTwoTimes,在调用它时不是&#34; undefined&#34;?感谢。

1 个答案:

答案 0 :(得分:1)

像这样:

var nameTwoTimes: function(name) {
    return name+" "+name;
};
var ctrs = {        
    ctr1: function($scope, $timeout) {
        $scope.name = '';
        $scope.getName = function() {
            return $scope.name+" "+$scope.name;
        };
    },
    ctr2: function($scope, $timeout) {
        $scope.name = '';
        $scope.getName = function() {
            nameTwoTimes($scope.name);
        };
    }
};