angularjs - 指令的 bool 范围值

标签 angularjs angularjs-directive

假设我有一个如下所示的指令:

<foo-bar bar-foo="booleanValue"></foo-bar>

booleanValue 这里属于父作用域 - 附加到上述指令元素所在 View 的 Controller 的作用域。

现在,在我的指令中,我已将指令定义如下:

app.directive('fooBar', function() {
    return {
        restrict: 'E',
        scope: {
            barFoo: '=barFoo'
        },
        link: function(scope, iElement, iAttrs) {
           scope.$watch('barFoo', function() {
               if(scope.barFoo !== true) return;
           });
           //Code to execute when barFoo is true
        }
    };
});

这里的问题是传递给 barFoo 的值是一个 bool 值,但它最终是一个字符串值。因此 `if (scope.barFoo !== true) 将始终成功,并且链接器函数永远不会执行。

我不想将代码更改为 if (scope.barFoo === "true")

如何将 bool 值传递到作用域?

编辑:我想在这里补充一点,booleanValue确实是一个 bool 值(通常作为 true 传递),由父 Controller 传递到指令中。只是当传递值时,它会转换为字符串而不是保留 bool 值。

最佳答案

假设该值在 Controller 中设置正确,则应将其作为 bool 值传递给指令。

这个plunker说明了这一点。

关于angularjs - 指令的 bool 范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001873/

相关文章:

javascript - Protractor - 如何处理大量动画的网站?

javascript - angularjs 中的 ng-show 不适用于 span

javascript - 调用服务方法后 AngularJs 更新指令

javascript - 将表单传递给指令 : undefined

javascript - Angular 路线不起作用

javascript - Angularjs - Kineticjs Canvas toDataUrl 无法在 Chrome 上工作 - 同一域上的图像

css - AngularJS 中的立方体动画

css - AngularJs 嵌套子菜单的 native 滑动切换无法正确更新高度

javascript - AngularJS 指令、范围、魔法和重复模板

javascript - Angular 理解链接函数