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

return '<span ng-bind-html="'+value+'">x</span>';不要手动绑定这些东西,而是在您的模板中进行绑定。<div>{{value}}</div>. 使用观察者来监听你的 propertyMap 上的变化,并在它发生变化时应用额外的逻辑(通过 ajax 加载)$scope.$watch()。如果您做的一切正确,您的模板将自动更新。(如果您不使用 Angular 的 $http 服务,您可能必须使用 $scope.$apply() 。

这是一个示例,您如何以角度编写此代码(未经测试的代码)

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 回答
0

pre在指令中使用。就像是:

pre: function(....) {
}

这将在链接之前被调用。

于 2014-09-02T20:47:20.650 回答