从指令获取数据并根据数据值更改图像

时间:2019-04-06 10:09:47

标签: angularjs controller

我想从random.js文件的模板属性中获取current.flag的值,然后在HTML文件中使用它。根据我将收到的标志的值,我希望更改图像。我想要一些帮助,因为我是Angular的初学者。 预先感谢

<section class="has-header">
  <div class="container">
    <div class="row">
      <div class="col-md-4 text-center">
          <img ng-src="{{current.flag === 'gr' ? 'images/image_1.png' : 'images/image_2.png'}}" />
      </div>
    </div>
  </div>
</section>

random.js

angular.module('app')
.directive('language', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        template: '<div class="languages-wrap pull-right">\
    <div class="languages f32">\
        <div ng-click="poped=!poped" class="current flag {{current.flag}}"></div></div>\
    <div class="language-selector" ng-show="poped">\
        <ul class="languages-list">\
            <li ng-repeat="l in langs">\
                <a ng-click="changeLang(l)" class="languages f32">\
                    <div class="flag {{l.flag}}"></div>\
                </a>\
            </li>\
        </ul>\
    </div>\
    </div>',
        controller: ['$scope', '$cookies', '$translate', '$route', '$location',
            function ($scope, $cookies, $translate, $route, $location) {
                $scope.poped = false;
                $scope.langs = [
                    {
                        iso: 'el',
                        flag: 'gr'
                    },
                    {
                        iso: 'en',
                        flag: 'us'
                    }
                ];

                $scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];

                $scope.changeLang = function (lang) {
                    $cookies.putObject('lang', lang, {expires: new Date(2020, 10, 10)});
                    $translate.use(lang.iso);
                    $scope.current = lang;
                    $scope.poped = false;
                    $location.search('lang', lang.iso);
                    $route.reload();
                };
            }
        ]
    };
});

1 个答案:

答案 0 :(得分:0)

u可以对html文件进行控制并添加

$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];

对控制器


如果我正确理解,您想使用另一个HTML文件中未与该指令连接的指令中的$scope.current值,如果是,则您可以在此html中添加一个控制器,然后添加

$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];

对此How to bind an AngularJS controller to dynamically added HTML?


  1. 制作控制器文件
  2. 将其添加到index.html,
  3. 将此内容添加到其中
var app = angular.module('myApp', []);
app.controller('exampleCtrl', function($scope, $cookies) {
    $scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];
}); 
    在html添加控制器中的
  1. 到section标签中
<section class="has-header" ng-controller="exampleCtrl">