AngularJS指令控制器解析插值属性?

时间:2013-10-25 23:37:41

标签: angularjs angularjs-directive

我只是觉得我这样做很糟糕,我想知道是否有更好的方法? 这是指令:

<myDirective myAttribute="{{val}}"></myDirective>

这是指令的控制器:

.controller('myDirective', ['$scope', '$attrs', function ($scope, $attrs) {
    $attrs.$observe('my-attribute', function (x) {
        $scope.myAttribute = x; // yay we finally have the interpolated value...
    });

由于我不想进入的多种原因,这很糟糕。有没有办法确保在调用控制器之前解析插值?

理想情况下,$ scope.myAttribute在调用控制器初始化程序时将具有插值。

编辑:我的主要目标是摆脱对该控制器所拥有的$ attrs的依赖。

2 个答案:

答案 0 :(得分:1)

也许最好的方法是:

    link: function (scope, element, attrs) {
        attrs.$observe('myAttribute', function(x) {
            scope.setMyAttribute(x);
        });
    }

然后:

.controller('myDirective', ['$scope', function ($scope) {
$scope.setMyAttribute = function (x) {
    $scope.myAttribute = x; // yay we finally have the interpolated value...
});

编辑:花了一些时间......这里有一个说明这个错误的傻瓜:

http://plnkr.co/edit/p46zuYbFAFCYH394zrUY?p=preview

请注意在child指令中使用“templateUrl”的重要性。只使用“模板”,错误就会消失。

答案 1 :(得分:1)

Angular 1.2 RC2或RC3打破了属性插值的一些事情。看到我提交的这个错误:

https://github.com/angular/angular.js/issues/4525

今天刚刚修好了。 永远不会在您的值中看到双花括号,这是一个错误。

但是,只要找到属性使用插值,它的评估就会变得异步。即使修复了这个错误,你也应该看到它的同步值为undefined(即如果你只是读取了$ attrs中的值)。这就是为什么你必须观察,所以价值会在它可用时立即发给你。

至于为什么它不能立即可用,它是动态的。 {{val}}的评估可能始终不同。这只是Angular的本质,一切都在不断更新。