0

イベントjsonデータの取得を担当するコントローラーがあり、データがある場合はデータでdomを更新し、そうでない場合はエラーメッセージでdomを更新します。

//Controller.js
myApp.controller('EventsCtrl', ['$scope','API', function ($scope, api) {
    var events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
}]);

//Directives.js
myApp.directive('notification', function () {
    return {
        restrict: 'A',
        link: notificationLink
    };
});
/**
 * Creates notification with given message
 */
var notificationLink = function($scope, element, attrs) {
    $scope.$watch('notification', function(message) {
        element.children('#message').text(message);
        element.slideDown('slow');
        element.children('.close').bind('click', function(e) {
            e.preventDefault();
            element.slideUp('slow', function () {
                element.children('#message').empty();
            });
       });
    });
};
//Services.js
...
$http.get(rest.getEventsUrl()).success(function (data) {
        // Do something with data
    }).error(function (data) {
        $window.notification = data;
    });

問題は、要素の変更がトリガーされることですが、 $window.notification には何も含まれていません。

編集:$watchで試してみました。

編集: html の両方のセットを 1 つのコントローラーに移動した後、DOM 操作は $watch() で機能します。お二方、ご協力ありがとうございました!

4

1 に答える 1

0

http リクエストの結果をコントローラーのスコープ変数に設定してみてください。次に、ディレクティブでその変数を監視します。

myApp.controller('EventsCtrl', ['$scope', 'API',
    function ($scope, api) {
        $scope.events = api.getEvents(); //events: {data: [], error: {message: 'Some message'}}
    }
]);

//Directives.js
myApp.directive('notification', function () {
    return {
        restrict: 'A',
        link: notificationLink
    };
});

var notificationLink = function (scope, element, attrs) {
    scope.$watch('events', function (newValue, oldValue) {
        if (newValue !== oldValue) {
            if (scope.events.data.length) {
                //Display Data
            } else {
                //Display Error
            }
        }
    });
};
于 2013-10-31T17:32:45.283 に答える