【问题标题】:Dynamically style based on angular value passed through基于通过的角度值动态样式
【发布时间】:2017-11-03 09:45:37
【问题描述】:

我有一个我想要设置样式的输入值,基于我从 angular 变量收到的值。所以在我的cshtml中,我有:

 <input type="{{d.input_type}}" ng-style={{d.input_type}} == "radio" ? 'width:40px;' : 'width:100px;" @*class="form-control"*@ @*ng-model="Customer.CustStatus"*@ name="question_answer" id="question_answer" required >

然后在我的角度 .js 文件中,我有以下内容:

 $scope.Question = {
                Question1: '',
                input_type: ''
            }

            $http.get('/Home/getUserInfo')
    .then(function (response) {
        $scope.Question = response.data;
        console.log("status:" + response.status);
        console.log("data: " + $scope.Question);

    }).catch(function (response) {
        console.error('Error occurred:', response.status, response.data);
    }).finally(function () {
        console.log("Task Finished.");
    });

根据我收到的返回值(“广播”或“文本”),我希望有不同的样式。例如,我希望单选按钮高度为 20px,文本必须为 40px。根据从“input_type”收到的文本值,我将如何对输入值进行条件样式设置。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript jquery css angularjs


    【解决方案1】:

    语法是

    <input ... ng-style="{'width': d.input_type == 'radio' ? '40px' : '100px'}" ...>
    

    因此,您首先指定要设置的属性,然后根据您的逻辑指定其值。

    【讨论】:

    • 感谢@NikolajDamLarsen,我从问题中复制了代码,并没有注意到双括号:)
    • 我不需要将d.input_type 放在两个 {} 之间?
    • @user1397978 不,Angular 已经假定传递给 ng-style 指令的所有内容都是一个 javascript 表达式,因此它不需要使用 {{ }} 对其进行插值。
    • Nikolaj 的答案更快,但这是逻辑 :)
    • @user1397978 当然,只需将语句括在括号内,这样您就可以确定它得到了正确的评估(d.input_type == 'radio' || d.input_type == 'checkbox')?...
    猜你喜欢
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多