在AngularJS初始化之前执行的函数

JS Function executing before AngularJS initialization

本文关键字:执行 函数 AngularJS 初始化      更新时间:2023-09-26

我已经被困了几个小时了(顺便说一下,我在JS/Angular方面不是特别好),也在寻找答案,但找不到出路,所以这是我的问题:我有一个函数,其目的是用其他东西替换文本中括号之间的内容,问题是我认为该函数在AngularJS之前运行,而我的文本是由AngularJS调用的(对不起,如果我用英语解释它有困难)。所以,我在搜索如何执行函数之后,或Angular之前。以下是所需的代码部分

HTML:

<ul class="list">
    <li ng-repeat="prop in props" ng-class="cssPropState(prop.state)" ng-click="checkProp(prop)" replace-directive>
         <p class="txtProps">{{prop.value}}</p>
    </li>
</ul>

JS:

exo2.directive("replaceDirective", function(){
    return function (scope, elements, attrs){
            var mytext = document.getElementsByClass("txtProps");
            var pattern = /'[(.*?)']/g;
            var results = mytext.firstChild.nodeValue.match(pattern);
            mytext = mytext.replace(results[0], "TEST1");
            mytext = mytext.replace(results[1], "TEST2");
    }
  }
)

文本由{{prop调用。值}},并且已经包含括号。我的问题是,结果总是返回null,因为它找不到文本,因为它还没有被Angular初始化。希望我的问题是理解,希望有人会很好地帮助我!

谢谢

尝试将replace-directive移动到<p id="txtProps">,如下所示:

<ul class="list">
    <li ng-repeat="prop in props" ng-class="cssPropState(prop.state)" ng-click="checkProp(prop)">
         <p id="txtProps" replace-directive>{{prop.value}}</p>
    </li>
</ul>
现在,链接函数的元素是p元素,所以链接函数看起来像:
exo2.directive("replaceDirective", function($timeout){
    return function (scope, element, attrs){
        $timeout(function() {
            var mytext = element.html();
            var pattern = /'[(.*?)']/g;
            var results = mytext.match(pattern);
            mytext = montext.replace(results[0], "TEST1");
            mytext = montext.replace(results[1], "TEST2");
            element.html(mytext);
        });
    }
});

更新:修改{{}}表达式中文本的最佳方法是使用filter。

你可以这样定义过滤器:

exo2.filter('replaceFilter', function(){
    return function(input) {
       var pattern = /'[(.*?)']/g;
       var result = input.match(pattern);
       var mytext;
       mytext = montext.replace(results[0], "TEST1"); // Here is something broken. montext is undefined. You need fix this.
       mytext = montext.replace(results[1], "TEST2");
       return mytext;
    }
});
然后,在html 中使用过滤器
<ul class="list">
    <li ng-repeat="prop in props" ng-class="cssPropState(prop.state)" ng-click="checkProp(prop)">
        <p class="txtProps">{{prop.value | replaceFilter }}</p>
    </li>
</ul>

当指令编译replaceDirective时。ng-repeat指令还没有完成。所以你应该等待它的完成,或者在$watch的执行中找到一个子元素。
exo2.directive("replaceDirective", function(){
    return function (scope, element, attrs){
        scope.$watch({
           var mytext = element.children('.txtProps'); // use class not id
           if(mytext.length) {
              var pattern = /'[(.*?)']/g;
              var results = mytext.text().match(pattern);
              mytext = montext.replace(results[0], "TEST1");
              mytext = montext.replace(results[1], "TEST2");
              element.html(mytext);
           }
        });
    }
});

PS:你不应该在ng-repeat中使用id。Id在文档中必须唯一