javascript - 范围变量更改时更改指令

标签 javascript angularjs

我正在使用 http 请求从我在 Controller 中使用的 json 文件中获取数据。

    app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) {
   //gets data from service 
        loaderService.getLoadedHtml().then(function (result) {
            $scope.fields = result.data;
        });
    }]);

当此 $scope.fields 更改为时,我需要更新指令

app.directive('dform', function () {
    return {
        scope: {
            action: '@',
            method: '@',
            html: '='
        },
        link: function (scope, elm, attrs) {
            var config = {
                "html": scope.fields
            };

            scope.$watch('fields', function (val) {
                elm.dform(config);
            });

            //console.log(config);
            //elm.dform(config);
        }
    };
})

下面是我如何使用这个指令

<div html="fields" dform></div>

但在我的例子中,当 $scope.fields 发生变化时,我的指令 $watch 函数中的 scope 未定义。

问题:

如何在 scope.$watch 函数中获取 scope.fields 的更新值?

最佳答案

您需要通过为其添加绑定(bind)来为指令提供对字段的访问权限:

scope: {
  action: '@',
  method: '@',
  html: '=',
  fields: '='
}

和 HTML:

<dform fields="fields" ...

该值可能是 undefined 第一次,然后你不想调用 dform:

scope.$watch('fields', function(newValue, oldValue) {

  if (newValue === oldValue) return;

  var config = {
    "html": newValue
  };

  elm.dform(config);
});

更新

使用这个 HTML:

<div html="fields" dform></div>

您只需要观看 html,不需要 $parent 或添加 fields 作为绑定(bind):

scope.$watch('html', ...

关于javascript - 范围变量更改时更改指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331412/

相关文章:

javascript - 需要有关 parseInt() 函数的帮助

javascript - 仅更改一个跨度以在 ng-repeat 内输入

javascript - 使用jquery获取点之前和点之后的值

javascript - 重置比例后在 Canvas 中重新缩放图像

javascript - 如何使用 div 单击事件更新输入

javascript - Angular : how to handle code provided by attributes

javascript - 在angularjs中使用来自rest服务的JSON对象

javascript - 访问 CORS 请求的响应 header

javascript - Firebase 身份验证失败

javascript - 即使 Angular 中没有数据,也会显示分页