AngularJS:如何恒定的对象绑定到一个指令 [英] AngularJS: how to bind a constant object to a directive

查看:92
本文介绍了AngularJS:如何恒定的对象绑定到一个指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个绑定使用范围的指示。在某些情况下,我要绑定恒定对象。例如,对于HTML:

I've created a directive with a binding using "scope". In some cases, I want to bind a constant object. For instance, with HTML:

<div ng-controller="Ctrl">
    <greeting person="{firstName: 'Bob', lastName: 'Jones'}"></greeting>
</div>

和JavaScript:

and JavaScript:

var app = angular.module('myApp', []);

app.controller("Ctrl", function($scope) {

});

app.directive("greeting", function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            person: "="
        },
        template:
        '<p>Hello {{person.firstName}} {{person.lastName}}</p>'
    };
});

虽然这个工作,它也导致JavaScript错误:

Although this works, it also causes a JavaScript error:

Error: 10 $digest() iterations reached. Aborting!

(小提琴证明了问题)

什么是恒定的对象绑定,而不会导致错误的正确方法?

What's the correct way to bind a constant object without causing the error?

推荐答案

下面是我想出的基础上,@ sh0ber的回答解决方案:

Here's the solution I came up with, based on @sh0ber's answer:

实现自定义链接功能。如果属性是有效的JSON,那么它是一个恒定值,所以我们只有一次评估。否则,手表和更新值正常(换句话说,尽量表现为 = 绑定)。 范围必须设置为真正,以确保所分配的值只影响该指令的该实例。

Implement a custom link function. If the attribute is valid JSON, then it's a constant value, so we only evaluate it once. Otherwise, watch and update the value as normal (in other words, try to behave as a = binding). scope needs to be set to true to make sure that the assigned value only affects this instance of the directive.

(实例上的jsfiddle)

HTML

<div ng-controller="Ctrl">
    <greeting person='{"firstName": "Bob", "lastName": "Jones"}'></greeting>
    <greeting person="jim"></greeting>
</div>

JavaScript的:

JavaScript:

var app = angular.module('myApp', []);

app.controller("Ctrl", function($scope) {
    $scope.jim = {firstName: 'Jim', lastName: "Bloggs"};
});

app.directive("greeting", function () {
    return {
        restrict: "E",
        replace: true,
        scope: true,
        link: function(scope, elements, attrs) {
            try {
                scope.person = JSON.parse(attrs.person);
            } catch (e) {
                scope.$watch(function() {
                    return scope.$parent.$eval(attrs.person);
                }, function(newValue, oldValue) {
                    scope.person = newValue;
                });
            }   
        },
        template: '<p>Hello {{person.firstName}} {{person.lastName}}</p>'
    };
});

这篇关于AngularJS:如何恒定的对象绑定到一个指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆