访问指令范围

时间:2013-10-31 17:01:25

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个控制器负责获取事件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移动到一个控制器后,DOM操作与$ watch()一起使用。感谢你们两位的帮助!

1 个答案:

答案 0 :(得分: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
            }
        }
    });
};