【问题标题】:accessing directive variable from parent's parent controller从父级的父级控制器访问指令变量
【发布时间】:2016-01-25 12:42:34
【问题描述】:

我有一个使用剑道编辑器的案例。

第一个控制器

app.controller('FirstController', ['$scope', function($scope) {
  $scope.Html = "<div> Hello World</div>";
}

Tempalte 的第二个控制器

app.controller('SecondController', ['$scope', function($scope) {
 $scope.Options= [{Options1, Option2}];
}

指令

app.directive('htmlEditor', ['$http', function($http) {
    return {

        restrict: 'EA',
        replace: true,
        scope: {
            documentName: "="
        },
        link: function (scope, element, attr) {               

            $http.get("ngview/TemplateEditor.html")
            .success(function (data) {
                element.html($compile(data)(scope));                    
            });              
        }
    }

}]);

TemplateEditor.html(我在模板中使用 SecondController)

<div ng-controller="SecondController">
<textarea kendo-editor k-ng-model="documentName" k-encoded="false" k-     
options="{{Options}}"></textarea>
 </div>

页面 HTML(我使用 FirstController 的地方)

<div ng-controller="FirstController" class="col-md-8">
    <div html-editor="HtmlEditor"
         document-name="Html">
    </div>
</div>

现在,如果对 html 进行一些更改,并将文本从 hello world 更改为“Hello Every Body”,我会得到相同的一个值,该值分配给它,

  $scope.Html = "<div> Hello World</div>";

JSFiddle 示例是 https://jsfiddle.net/aqdasiftekhar/HB7LU/19160/

【问题讨论】:

  • 我在你的代码中看不到 $scope.Html 变量在除第一个控制器之外的任何地方被引用,所以我看不到 kendo-editor 怎么知道值第一,更别说能更新了。
  • 我的错误,document-html="DocumentHtml" 实际上是 document-html="Html"
  • 但是您的指令范围需要 document-name 属性,而不是 document-html
  • 再次修复,感谢高亮,其实我打错了,现在我更正了。问题依然存在
  • 你为什么不使用templateUrl

标签: javascript angularjs angularjs-directive kendo-ui angularjs-scope


【解决方案1】:

您在 plunkr 上的代码的工作示例在这里会很有用,但乍一看,问题似乎是:

k-ng-model="documentName"

你的意思可能是:

k-ng-model="{{documentName}}"

这将导致 documentName 被解析为 Html,因此将 textarea 绑定到 $scope.Html。

【讨论】:

  • @Aqdas,您能否提供示例工作 plunker 和您的代码?
  • @Aqdas,您展示的示例没有 2 个控制器,它只有 1 个。
  • plnkr.co/edit/X9mIC3AOR33IV4gTlwgl 我创建了 plunker,但我不知道缺少什么,因为我使用 jsfiddle
  • @Aqdas,如果对你有用,你可以提供 jsfiddle
  • 这里它正在工作,但我仍然有一个角度问题。如果你能帮忙解决
【解决方案2】:

所以在挣扎了很久之后,

我通过将父级 (SecondController) 父级 (Directive's Scope) 父级 (FirstController) 对象引用到模板文件中的 k-ng-model 来修复

TemplateEditor.html 更改以下代码

<div ng-controller="SecondController">
 <textarea kendo-editor k-ng-model="documentName" k-encoded="false" k-     
 options="{{Options}}"></textarea>
</div>

收件人

<div ng-controller="SecondController">
   <textarea kendo-editor k-ng-model="$parent.$parent.$parent.Html" k-  
   encoded="false" k-options="{{Options}}"></textarea>
</div>

经过上述修改后,我不需要指令中定义的变量

scope: {
        documentName: "="
},

感谢所有试图帮助我的人:-)

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 2023-03-28
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多