在某些条件下自动调用的函数

时间:2015-09-21 03:02:08

标签: angularjs

我有这样的代码:

<div class="row"
     ng-repeat="x in companies|orderBy:'id' ">
    <div class="col left" >
        <button ng-click="viewPublicId(x.id)">{{x.companyname}}</button>
    </div>
    <div class="col left">
        {{x.address}}
    </div>
    <div class="col left">
        {{x.telephone}}
    </div>
</div>

我想要做的是添加一个检查:当companies.size = 1时,会自动调用函数viewPublicId。我怎样才能做到这一点?感谢。

已更新:viewPublicId函数:

$scope.viewPublicId = function viewPublicId(companyid) {
    var url = "http://7cf8d64c.tunnel.mobi/yii2-basic/web/index.php?r=restpublic/view&companyid=" + companyid;
    console.log("debug", url);
    $http.get(url)
    .success(function (response)
    {
    console.log("debug PublicId",response);
    if(response.length==33)
    $scope.publicids = null;
    else
    $scope.publicids = response;
    })
    .error(function (response)
    {
    console.log("debug PublicId",response);
    $scope.publicids = null;
    });

    $state.go('tabs.publicidlist');
}

1 个答案:

答案 0 :(得分:0)

在你的控制器中:

if ($scope.companies.length === 1) {
    $scope.viewPublicId();
}

如果您的companies可以动态更改,并且每次更改时都需要调用该函数,请使用$watch

$scope.$watch('companies', function () {
    if ($scope.companies.length === 1) {
        $scope.viewPublicId();
    }
}, true);