AngularJS - 如何将带有插值数据的对象(在运行中创建)传递给自定义指令

时间:2022-11-26 23:11:13

I would like to create a custom directive to which I can pass an object (created on the fly) with interpolated values.

我想创建一个自定义指令,我可以使用插值传递一个对象(动态创建)。

Example:

Newly created array as a parameter:

新创建的数组作为参数:

{userName: vm.data.name}

vm.data.name should be replaced with controller data.

vm.data.name应替换为控制器数据。

Here is my code:

这是我的代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom directive</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script>
(function(angular) {
'use strict';
angular.module('testDirectiveApp', [])
  .controller('testController', ['$scope', function($scope) {
    var data = {
      name: 'ABC'
    }

    var vm = this;
    vm.data = data;
  }])
  .directive('customDirective', ['$interpolate', function($interpolate) {
    return {      
      scope: {
        customParam: '='
      },
      link: function(scope, element, attributes){
        scope.$watch('customParam', function() {
          console.log(attributes.customParam, $interpolate(attributes.customParam)(scope), scope.$eval(attributes.customParam));
        });
      }
    };
  }]);
})(window.angular);
  </script>
</head>
<body ng-app="testDirectiveApp">
  <div ng-controller="testController as vm">
    Name: <input ng-model="vm.data.name"> <hr/>
    <div custom-directive custom-param="{userName: vm.data.name}"></div>
    <p>{{vm.data.name}}</p>
  </div>
</body>
</html>

Is this doable? What I'm doing wrong?

这可行吗?我做错了什么?

Best Regards,

1 个解决方案

#1


1  

The problem is that you are trying to access a scope variable with the attributes object, and not the scope object.

问题是您尝试使用attributes对象而不是范围对象来访问范围变量。

In your directive, change attributes.customParam to scope.customParam

在您的指令中,将attributes.customParam更改为scope.customParam

http://plnkr.co/edit/1o4746GamtIcwHekoKyl?p=info

#1


1  

The problem is that you are trying to access a scope variable with the attributes object, and not the scope object.

问题是您尝试使用attributes对象而不是范围对象来访问范围变量。

In your directive, change attributes.customParam to scope.customParam

在您的指令中,将attributes.customParam更改为scope.customParam

http://plnkr.co/edit/1o4746GamtIcwHekoKyl?p=info