在不使用隔离范围angularjs自定义指令的情况下获取属性对象

get attribute object without using isolated scope angularjs custom directive

本文关键字:指令 情况下 获取 对象 属性 自定义 angularjs 隔离 范围      更新时间:2023-09-26

假设我有这个自定义指令

<div ng-controller="MyCtrl">
    <select ng-model="selectBox">
         <option value="test">test</option>
    </select>
    <my-directive select="selectBox"></my-directive>
</div>
myApp.directive('myDirective', function () {
    return {
        restrict:'EA',
        function (scope, element, attr) {
           var atrib = scope.$eval(attr.select)
           console.log(atrib);
    }
   }
});

每当我执行console.log命令时,它都会返回undefined值。我听说过孤立范围。但对于这种环境,我不想使用孤立的作用域。。

问题是我该如何实现这些目标?

更新我根据@dfsq的答案更新了这个问题,但它仍然没有

更新显然,如果我使用scope包装attr.select$eval并将属性从{{}}更改为对象包装,我只使用字符串,它会起作用!非常感谢你们的回答!

甚至不确定如何获得任何控制台日志输出。按照你定义指令的方式,这是不可能的。您正在使用指令作为元素,但其定义将其用作属性。更改为:

myApp.directive('myDirective', function() {
    return {
        restrict: 'E',
        link: function(scope, element, attr) {
            var atrib = attr.select;
            console.log(atrib);
        }
    }
});

同样,您需要将resrict属性声明为E"元素"。如果您省略它(如果您只提供链接函数,就会发生这种情况),则默认为A"属性"。

如果您想在select中的每个选项更改后在控制台中看到新的值,可以通过以下方式来完成。

<div ng-controller="MyCtrl">
    <select ng-model="selectBox" ng-options="item for item in items"></select>
    <my-directive select="{{selectBox}}"></my-directive>
</div>

JS代码:

myApp.directive('myDirective', function () {
    return {
        restrict:'E',
        scope: {
            select: '@select'
        },
        link: function (scope, element, attr) {
           scope.$watch('select', function(newValue){
               console.log(attr.select); //changed every time after a new select
           });
    }
   }
});
function MyCtrl($scope) {
    $scope.items = ['test1', 'test2', 'test3'];
    $scope.selectBox = $scope.items[0]; //default select's value
}

我为您附上了JSFiddle示例。