AngularJS模板与指令中的templateURL

时间:2015-06-14 13:27:58

标签: javascript angularjs angularjs-directive

我有一个如下定义的指令:

class RunnableThread
{
    public static void main(String[] args)
    {
        MyThread t1= new MyThread();
        Thread firstThread= new Thread(t1);
        firstThread.start();
        System.out.println("Thread Main");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread Main i = " + i);
        }
        System.out.println("Exit from Main");
    }
}

class MyThread implements Runnable
{
    public void run()
    {
        System.out.println("Thread MyThread");
        for(int i=1;i<=5;i++)
        {
            System.out.println("From thread MyThread i = " + i);
        }
        System.out.println("Exit from MyThread");
    }
}

app.directive('itemComments', ['ajax', function(ajax) { return { restrict: 'A', templateUrl: URL + 'public/Pages/Homepage/ajax/getCommentsTpl', controller: 'ItemLibraryController', controllerAs: 'itemLibraryCtrl', link: function(scope, element, attr) { var $element = $(element); scope.$watch(function(scope) { return $element.find('li').length > 0; }, function(finished) { if(finished) { autosize($element.find('textarea')); } }); } }; }]); 指定的模板返回如下内容:

"templateUrl"

在ItemLibraryController中,我定义了在textarea上的keyup上访问的方法commentPost()。 问题是... <textarea class="form-control textarea-resize" ng-keyup="commentPost($event)" ng-model="textComment"></textarea> ... 而不是textarea中输入的值。如果我在html $scope.textComment = undefined中修改,那么textarea中的值可以在ng-model="$parent.textComment"中找到。

PS。使用&#34;模板&#34;而不是&#34; templateUrl&#34;在指令定义中,ng-model问题消失了。

我的问题是:

  1. 为什么我必须使用$ parent.textComment,因为模板的范围是ItemLibraryController?

  2. 为什么使用templateUrl会为模板中的ng-models创建另一个范围?

  3. 为什么在使用&#34;模板&#34;而不是&#34; templateUrl&#34;在指令定义中,ng模型问题消失了吗?

  4. 如何在不使用$ parent.textComment的情况下访问textComment?

1 个答案:

答案 0 :(得分:1)

解决此问题的问题是使用AngularJS的点规则, so that the object will for [**prototypal inheritance**][1]. For that you need to create and object and add the textComment in it, so the object will look like $ scope.library = {} then textComment will be placed in it. Also you need to make add范围:true`到说该指令将遵循对象的继承。

<强>模板

...
<textarea class="form-control textarea-resize" 
   ng-keyup="commentPost($event)" 
   ng-model="library.textComment">
</textarea>
...

<强>指令

app.directive('itemComments', ['ajax', function(ajax) {
    return {
        scope: true, //<--added here
        restrict: 'A',
        templateUrl: URL + 'public/Pages/Homepage/ajax/getCommentsTpl',
        controller: 'ItemLibraryController',
        controllerAs: 'itemLibraryCtrl',
        link: function(scope, element, attr) {
            //code here
        }
    };
}]);