0

いくつかの情報を取得する ajax 呼び出しを実行しています。 <span id="test" abc-dir="test"> </span>

ここで、ajax 経由で返された上記の情報に対して実行する必要がある角度ディレクティブもあります。

問題は: Angular ディレクティブが最初に開始され、DOM で abc-dir を見つけようとしますが、Ajax 呼び出しが完了していないため、何もしません。最初にajax呼び出しを起動してから、Angularディレクティブを呼び出す方法は?

私のHTMLコード:

<body ng-app="TestApp" ng-controller="TestCtrl" ng-init="init()"> <div class="test" id="testid"></div> <script> require( ['jquery'], function($) { $.ajax({ type: "GET", url: "....", success: function(data) { document.getElementById('testid').innerHTML = data } }); }); </script>

私の Angular ディレクティブ コードは次のとおりです。

angular.module('TestApp', ['ngSanitize']) .directive('abcDir',['abcPropertyMap',function(abcPropertyMap) { return { restrict: 'A', template: function(elm,attrs){ var value = abcPropertyMap[attrs.abcProperty]; return '<span ng-bind-html="'+value+'">x</span>'; } } }])

4

2 に答える 2

0

preディレクティブで使用します。何かのようなもの:

pre: function(....) {
}

これは、リンクする前に呼び出されます。

于 2014-09-02T20:47:20.650 に答える
0

return '<span ng-bind-html="'+value+'">x</span>';このようなものを手動でバインドしないでください。代わりにテンプレートで行ってください。<div>{{value}}</div>. ウォッチャーを使用して propertyMap の変更をリッスンし、変更されたらすぐに追加のロジックを適用します (ajax を介して読み込まれます) $scope.$watch()。すべてを正しく行うと、テンプレートが自動的に更新されます。(angular の $http サービスを使用していない場合は、 $scope.$apply() を使用する必要がある場合があります。

これをangularで記述する方法の例を次に示します(コードはテストされていません)

js 部分:

angular.module('stackoverflow', [])
.controller('questionsCtrl', function($scope, $http) {
    $scope.questions = null;

    $http.get('stackoverflow.com/questions').then(function(questions) {
        $scope.questions = questions;
    });
})
.directive('questionsList', {
    restrict: 'EA',
    templateUrl: 'directives/questionsList.html',
    scope: {
        questions: '=',
    },
    controller: function($scope) {
        $scope.$watch('questions', function(newValue, oldValue) {
            if (newValue !== null) console.log('all questions loaded');
        });
    }
})

そしてhtml:

<!-- index.html -->
<html ng-app="stackoverflow">
<head></head>
<body>
    <div ng-controller="questionsCtrl">
        <questions-list questions="questions"></questions-list>
    </div>
<body>
</html>

<!-- directives/questionsList.html -->
<ul>
    <li ng-repeat="question in question track by $index">
        {{question.title}}
    </li>
</ul>

ajax を介して html をロードしていて、それをページに (角度機能を使用して) レンダリングしたい場合は、ng-includeディレクティブの使用を検討してください。$compileそれ以外の場合は、サービスを使用して自分で html をコンパイルする必要があります。

// example of how to compile html in your controller
// consider thou that $compiling or modifying html from within your controller is considered as bad practice
.controller('someCtrl', function($scope, $element, $compile, $timeout) {
    var scope = $scope.$new();
    scope.question = {title: 'angular stuff'};
    $element.append(
        $compile('<div>{{question.title}}</div>')(scope)
    );

    // will update your html in 2 seconds
    $timeout(function() {
        scope.question.title = 'javascript stuff';
    }, 2000);
});
于 2014-09-02T21:12:52.080 に答える