【问题标题】:angularjs model view update through angular directive通过 angular 指令更新 angularjs 模型视图
【发布时间】:2014-07-22 02:45:08
【问题描述】:

我正在尝试使用角度指令中的模型更新我的视图,这是我创建的指令

app.directive('aboutOptions', [function() {
        return {
            restrict: 'C',
            scope: {
                testing: '='
            },
            transclude: true,
            link: function(scope, elem, attr) {
            scope.$watch(attr.ngModel, function() {
                console.log(scope.$eval(attr.ngModel));
                scope.testing = scope.$eval(attr.ngModel);
            });
        }
    }
}]);

这里是html模型,文件名是ab.html

<input type="text" class="about-options" ng-model="testing" />

这里是要更新的视图,文件名是show.html

<h2 class="about-options">{{testing}}</h2>

ab.html 文件将作为模板加载到 jquery ui 对话框 中,而我的 show.html 文件在主页中

如果我删除

scope: {
       testing: '='
},

控制台正在显示我正在输入的内容

更新 - 1

尝试了以下更改

testing: '=test'

在html中

<input type="text" class="about-options" ng-model="testing" />

<h2 class="about-options">{{test}}</h2>

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    您最后对范围所做的事情是隔离范围,因此如果在使用该指令的元素上找不到名为 testing 的属性,您应该会在控制台中看到错误。如果您需要一个隔离范围(很多时候这是一个好主意),那么您需要提供 testing="someScopeVar" 作为该指令应用到的元素的属性。

    【讨论】:

    【解决方案2】:

    看看这个 repo 看看我是怎么做的。

    https://github.com/jedininjaster/angular-mask-money/blob/master/demo/js/angular.maskMoney.js

    还可以查看 angular-ui 掩码指令。这就是我构建指令的方式。

    https://github.com/angular-ui/ui-utils/blob/master/modules/mask/mask.js

    抱歉,我现在没有时间写一个完整的解释。明天试试更新

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 2020-03-03
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多