【问题标题】:Angularjs ns-style change via Controller通过控制器更改 Angularjs ns 样式
【发布时间】:2014-10-16 20:31:56
【问题描述】:

我正在尝试更改 div 的背景颜色。我的html代码如下:

<div ng-style="{'background-color': backgroundImageInfo}">
    <input type="file" onchange="angular.element(this).scope().fileThatChangeBackground(this)" />
</div>

在控制器中挖掘 js 代码:

$scope.backgroundImageInfo='red';
$scope.fileThatChangeBackground = function() {
    alert($scope.backgroundImageInfo);
    $scope.backgroundImageInfo='blue';
};

控制器的第一行将背景颜色更改为红色。当我将文件设置为输入警报时显示“红色”并且没有将背景颜色更改为蓝色。当我更改输入文件(触发功能)警报显示“蓝色”并且再次没有更改背景颜色。当我从函数中更改值时,为什么 ng-style 不改变颜色?

【问题讨论】:

    标签: angularjs controller ng-style


    【解决方案1】:

    由于您是从 Angular 外部调用 fileThatChangeBackground 函数,因此如果您希望它起作用,则需要执行 $scope.$apply。像这样:

    angular.module('testApp',[])
    .controller('testCtrllr', function($scope){
        $scope.backgroundImageInfo='red';    
        $scope.fileThatChangeBackground = function(scope) {                    
            $scope.$apply(function(){
                $scope.backgroundImageInfo='blue';
            });
        };
    });
    

    Working example

    【讨论】:

    • 非常感谢您的回答
    • @GoncharDenys 没问题,随时!
    猜你喜欢
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2020-05-08
    相关资源
    最近更新 更多