AngularJs,在没有隔离的情况下将指令属性添加到范围

AngularJs, add directive attribute to scope without isolation

我创建了一个使用父作用域的 directivedirective 应该接受一个属性,即

<my-nice-new-directive data-hide-icon="true" />

但我不想隔离范围。是否可以只将属性添加到 $scope?

考虑使用 $parse 服务。

.directive('myNiceNewDirective', function () {
    return {
        restrict: 'AE',
        controller: function ($scope, $attrs, $parse) {
            var hideIcon = $parse($attrs.hideIcon)($scope);
        }
    };
})

或者您可以只计算变量 data-hide-icon="{{isIconHidden}}",在这种情况下您可能想要观看它。

.directive('myNiceNewDirective', function () {
    return {
        restrict: 'AE',
        scope: true, //this is not necessary but could be useful
        controller: function ($scope, $attrs) {
            $scope.$watch(function () {return $attrs.hideIcon;}, function (newValue, oldValue) {
               //react to change...
            });
        }
    };
})