angularjs自定义指令值的变化

时间:2013-09-15 10:45:30

标签: angularjs

我有以下代码(它在jsfiddle上不起作用,但如果你把它保存为index.html就可以了)

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
    <script>
      var photos = [
        {"url":"http://archive.vetknowledge.com/files/images/guinea-pig---tan.jpg"},
        {"url":"http://www.rfadventures.com/images/Animals/Mammals/guinea%20pig.jpg"}
      ];

      angular.module('app', [])

      .directive('ngBackground', function(){
        return function(scope, element, attrs){
          var url = attrs.ngBackground;
          element.css({
            'background-image': 'url(' + url + ')',
            'background-size' : 'cover'
          });
        };
      })

      .controller('PhotosCtrl', function($scope){
        $scope.photos = photos;
        $scope.flags = {
          modalOpen: false,
          imgSrc: null
        };

        $scope.doModal = function(url){
          if(url != false) {
            $scope.flags.imgSrc = url;
            $scope.flags.modalOpen = true;
          } else $scope.flags.modalOpen = false;
        };

        $scope.sourcifier = function(url){
          var temp = document.createElement('a');
          temp.href = url;

          if(temp.hostname.substring(0, 4) == 'www.')
            return temp.hostname.substring(4);
            else return temp.hostname;
        };
      });
    </script>
  </head>
  <body>
    <div ng-controller="PhotosCtrl">

      <div ng-repeat="photo in photos" class="item">
        <img ng-src="{{photo.url}}" ng-click="doModal(photo.url)">
        <p><a ng-href="{{photo.url}}" target="_blank">{{sourcifier(photo.url)}}</a></p>
      </div>

      <div ng-show="flags.modalOpen" ng-click="doModal(false)">
        <div ng-background="{{flags.imgSrc}}">my background should be of the clicked image</div>
      </div>

    </div>
  </body>
</html>

这基本上从阵列“照片”加载图像并显示它们。我想要实现的是使用自定义创建的ng-background指令将div的背景图像更改为单击的图像src。

根本不起作用!现在,我确定flags.imgSrc是正确的,因为如果我在img标签上使用ng-src,那么 就可以了。似乎更像是自定义指令ng-background没有“刷新”该标志的值。

任何想法为什么以及如何解决这个问题?提前谢谢。

1 个答案:

答案 0 :(得分:2)

flags.imgSrc更改需要$watch

.directive('ngBackground', function(){
     return function(scope, element, attrs){
          var url = attrs.ngBackground;

          scope.$watch(url,function(n,o){
             if(!n) return;

             element.css({
              'background-image': 'url(' + n + ')',
              'background-size' : 'cover'
            });

          },true);

        };
    });

看看:http://plnkr.co/edit/JXmG7L?p=preview

更新:但听取元素“attributes”更改的正确方法是$observe method

    attrs.$observe("ngBackground",function(n,o){ /* same handler code */ });

更新了plunk:http://plnkr.co/edit/fOOCOd?p=preview