【问题标题】:angularJS: how to break the link between the model and the viewangularJS:如何断开模型和视图之间的链接
【发布时间】:2012-07-29 17:44:45
【问题描述】:

我想知道是否有可能在运行时断开模型和视图之间的链接。
在以下示例中,所有内容都链接在一起(通过 text 模型)。当我单击按钮时,我想让 Angular 不再更新最后一个输入(例如启动一些 jquery 效果...)。

<html ng-app>
  <head>
    <script src="angular-1.0.1.js"></script>
  </head>
  <body>
    <input ng-model="text"/><br/>
    <input ng-model="text"/><br/>
    <input ng-model="text"/><input type="button" value="<- break!" ng-click="???"/><br/>
  </body>
</html>

我的真实案例在这里:http://jsfiddle.net/5JZPH/10/
在 jsfiddle 示例中,我希望当我按下“+”按钮时,旧值(正在消失的值)不再改变。

【问题讨论】:

  • 小提琴的预期/期望行为是什么?
  • 那么如果你删除 ng-model 属性它不会失去关联?
  • @Soubok 你真的需要断开模型和视图之间的链接吗?像这样的东西怎么样:jsfiddle.net/5JZPH/13
  • @Soubok 更好的例子:jsfiddle.net/5JZPH/14
  • @ArtemAndreev,这是个好主意,但我真的需要我的“淡化”输入成为模型的一部分。

标签: javascript angularjs


【解决方案1】:

您可以淡出 jQuery 克隆的 html 元素:http://jsfiddle.net/5JZPH/29/

HTML:

<div ng-app="test">
    <input type="button" value=" + " ng-click="index = index + 1"/>
    <input ng-model="index" smooth="index" style="display:block"/>
    [{{index}}]
</div>

JavaScript:

angular.module('test', [])
.directive('smooth', function() {
    return {
        transclude: 'element',
        priority: 750,
        terminal: true,
        compile: function(element, attr, linker) {
            return function(scope, iterStartElement, attr) {

                var prevClone = null;

                scope.$watch(attr.smooth, function() {

                    var newScope = scope;

                    linker(newScope, function(clone) {

                        if ( prevClone ) {

                            newPrevClone = prevClone.clone();
                            prevClone.after(newPrevClone);
                            prevClone.remove();
                            newPrevClone.fadeOut(2000, function() { $(this).remove() });
                        }

                        iterStartElement.after(clone);

                        prevClone = clone;
                    });
                });
            }
        }
    };
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2012-06-28
    相关资源
    最近更新 更多