在ng-repeat

时间:2016-10-12 23:32:12

标签: javascript angularjs

我使用属性指令来更新DOM,这是一个名为profileImage的变量。属性指令名为ppt-profile-icon,只要它不在ng-repeat内,就可以正常工作。我已经查看了Stackoverflow上的大量问题,但没有找到解决方案。

这是我的HTML:

<div class="img-preview" ng-style="{'background-image': 'url(' + profileImage + ')'}"></div>


<ul class="dropdown-menu pre-defined-icons" uib-dropdown-menu role="menu" aria-labelledby="single-button">
    <li ng-repeat="predefinedImage in vm.predefinedImages">
        <a>
            <img ppt-profile-icon src="{{predefinedImage}}" width="100%" />
        </a>
    </li>

    <!--This, outside of the ng-repeat will work-->
    <li>
        <a>
            <img ppt-profile-icon src="content/img/people/noProfileIcon.svg" width="100%" />
        </a>
    </li>
</ul>

这是我的指示:

angular
    .module('app.core')
    .directive('pptProfileIcon', function ($timeout) {
        //link function for DOM Minipulation
        function linkFunction(scope, elem, attrs) {
            elem.bind('click', function () {
                scope.profileImage = attrs.src;
                scope.$apply();
            });

        }//end

        //Directive Declaration
        return {
            restrict: "A",
            controller: ['$scope', function ($scope) {
                //sets enviornment
            }],
            link: linkFunction
        }//end

    });//end

在我的link函数中,我尝试过:

attrs.$observe('src', function (val) {
    $timeout(function () {
        scope.profileImage = val;
        scope.$apply();
    });
});

$timeout(function () {
    scope.profileImage = attrs.src;
    scope.$apply();
});

2 个答案:

答案 0 :(得分:1)

问题是,您的指令中的scopengRepeat指令的范围,而不是父级,因此您只在转发器中设置profileImage

我选择了可​​执行的绑定

.directive('pptProfileIcon', function() {
    return {
        restrict: 'A',
        scope: {
            pptProfileIcon: '&'
        },
        link: function(scope, elem) {
            elem.on('click', function() {
                scope.pptProfileIcon({
                    profileImage: elem.prop('src')
                });
                scope.$apply();
            });
        }
    }
})

然后,在控制器范围内创建一个函数来设置图像

$scope.setProfileImage = function(image) {
    $scope.profileImage = image;
};

并像这样设置模板

<img ppt-profile-icon="setProfileImage(profileImage)" ng-src="{{predefinedImage}}" />

Plunker demo〜http://plnkr.co/edit/GqFXqZW5AmLCyWHblBDN?p=preview

答案 1 :(得分:1)

在parend-child范围之间进行交互时,你应该始终在 ngModels 中使用object(有关详细信息,请参阅https://github.com/angular/angular.js/wiki/Understanding-Scopes),所以只需在原语之前添加vm.model就足够了: / p>

<div class="img-preview" 
     ng-style="{'background-image': 'url(' + vm.model.profileImage + ')'}"></div>

并在链接功能中:

    //link function for DOM Minipulation
    function linkFunction(scope, elem, attrs) {

        elem.bind('click', function () {
          scope.vm.model.profileImage = attrs.src;
          scope.$apply();
        });

    }//end

plunker:http://plnkr.co/edit/jddW7zURZoyLA8MKkm6t?p=preview