如何根据条件为 ng-model 赋值

How to assign ng-model a value based on a condition

本文关键字:ng-model 赋值 条件 何根      更新时间:2023-09-26

好的,我正在尝试创建一个Web链接指令。链接需要 URL 和文本值。如果文本值没有值 - 文本值将等于 url。例如:

<a href="http://google.com">http://google.com</a>

链接具有文本值的示例

<a href="http://google.com">Search engine</a>

下面的代码中有两个输入标记,用于记录 URL 值和文本值。如果文本值为空,则文本值将等于 url 值。这是我的指令的代码:

Website1.directive('inputlink', function () {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            urlvalue: '=',
            textvalue: '='
        },
        template:   '<div>' +
                        '<input type="text" ng-model="urlvalue" value="{{urlvalue}}" placeholder="Enter link URL"></input>'+
                        '<input type="text" ng-model="textvalue" value="{{textvalue}}" placeholder="Enter text"></input>' +
                    '</div>'
    }
});
因此,如果文本值

为空,它将等于urlvalue,否则文本值将具有自己的值。

您需要在函数中更改它。

link: function( $scope, $element, $attributes ) {
    if(!$scope.textvalue) {
       $scope.textvalue = $scope.urlvalue;
    }
}

根据您的要求,您可能还需要$watch它。