Angularjs自定义指令使用指令 Controller 变量

标签 angularjs angularjs-directive angularjs-ng-model

我创建了一个自定义指令,其中有一个我需要在其他 View 中使用的数组。例如,假设我的指令内容中有一个输入框,我必须在另一个 Controller 中使用它的值,我该如何实现?我尝试使用 ng-model 但没有成功。

这是我的 Controller :

angular.module("demo", []);

angular.module("demo").controller("demoController", function ($scope) {
    $scope.name = "John";
});

angular.module("demo").controller("directiveController", function ($scope) {

    $scope.name = "John Doe";

});


angular.module("demo").directive("passVariable", function () {
    return {
        restrict: 'AEC',
        require: "ngModel",
        templateUrl: "content.html",
        link: function (scope, element, attr, ngModel) {
            scope.$watch(function () {
                return ngModel.$modelValue;
            },
            function (modelValue) {
                console.log(modelValue);       
            });

        }
    }
});

和 HTML 文件:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.4.0-beta.5" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
  </head>

  <body ng-app="demo" ng-controller="demoController">
    <div>
      <pass-variable ng-model="name"></pass-variable>
    </div>
    <br />
    <div>
        Second directive textbox:       <input type="text" ng-model="name" pass-variable="" />
    </div>
    <br />
    <div>
        Main textbox:       <input type="text" ng-model="name" />
    </div>
  </body>

</html>

和content.html

<div ng-controller="directiveController">
    Content Textbox: <input type="text" ng-model="name"/>
</div>

这是我的 plunker:http://embed.plnkr.co/rzlUQM6FBI3Sll4F8WaG/preview

顺便说一句,我不知道为什么 plunker 不加载 content.html

更新 我发现我应该在指令 controller: directiveController 中添加 Controller 并删除 ng-controller='directiveController'content.html

最佳答案

如果我没理解错的话,你的问题出在 content.html 中的 ng-controller。

<div ng-controller="directiveController">
  Content Textbox: <input type="text" ng-model="name"/>
</div>

删除 ng-controller 后,所有三个输入字段都将同步。

它不起作用的原因是您在指令模板中定义了一个新 Controller ,它有一个 $scope.name 属性隐藏了原始 Controller 的属性。

这是一个 plnkr

关于Angularjs自定义指令使用指令 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852368/

相关文章:

javascript - 在 AngularJS 动态电子邮件验证元素中,当我填写电子邮件检查元素时,它被重置

javascript - AngularJS - 访问子指令 Controller

angularjs - AngularDart: “static _nop(e) => e;”是什么意思

javascript - 将属性值传递给指令模板

javascript - 为什么更改姓氏时模型中的全名没有更新?

javascript - angularJs 指令中 templateUrl 的正确路径应该是什么?

javascript - 如何使用带有复选框值的 ng-model?

javascript - 拖动标记后 Ng-map 获取地址

angularjs - 配置中的 Angular 别名路由无需重定向

javascript - AngularJS - 重用 HTML 模板代码,无需 AJAX 调用