javascript - AngularJS 中的条件 View

标签 javascript angularjs

我有一个关于 AngularJS 中条件部分类似 View 的问题。下面的例子不是很理想。它还返回属于行 $compile(element.contents())(scope) 的错误这说明我不能使用 scope作为一个函数 - 但否则它不会正确渲染所有内容。用例如下:

  1. 我正在请求一条经过 $http 的路线返回一个对象数组

  2. 我是ng-repeat返回对象数组

  3. 对于每个对象(我们称之为 obj )一个 obj.view_edit值已给出。

  4. 如果obj.type等于 plugin ,一个<plugin></plugin>指令已插入

看起来像:

 <plugin view="content.view_edit"></plugin>

我的指令如下所示:

 directive('plugin', function($compile) {
    var linker = function(scope, element, attrs) {
        console.log(scope.view);
        element.html(scope.view).show();
        $compile(element.contents())(scope);
    }
    return {
        restrict:"E",
        link: linker,
        scope: {
            view:'='
        }
    }
})

您还有更好的解决方案吗?

最佳答案

在处理更复杂的问题之前,您不需要在链接函数中手动进行 DOM 操作来隐藏/显示或 $compile 。只需使用 native ng-if 指令即可。

<div ng-repeat="obj in objects">
    <div ng-if="isPlugin(obj)">
        <plugin view="obj.view_edit"></plugin>
    </div>
    <div ng-if="!isPlugin(obj)">
        This is not a plugin.
    </div>
</div>

然后,您的作用域中就会有一个被 ng-if 引用的函数。这可以使 HTML 保持干净并且尽可能清晰地保留逻辑。

scope.isPlugin = function (obj) {
    return obj.type === 'plugin';
}

关于javascript - AngularJS 中的条件 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049582/

相关文章:

javascript - Angular JS 属性指令采用变量

javascript - DeepCopy 用于 AngularJs 对象中包含的所有字段和数组

javascript - 使用选中的框删除存储在本地内存中的项目 Jquery

javascript - 用js或vbs触发点击href按钮

javascript - 文本框在 javascript 警报后更改高度和边框宽度

javascript - 每个选项卡的 AngularJS 唯一选项卡数据

javascript - 如何使用 d3.time.scale 为一天中的每一小时和一周中的每一天创建标签

javascript - Google Maps API Geocoder 不按 placeId 返回位置

javascript - AngularJS 中超出了最大调用堆栈大小

javascript - 在 angular-ui-bootstrap 轮播上设置事件幻灯片