在指令内访问范围
Accessing scope within directive
我有一个控制器,负责获取事件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.通知中没有任何内容。
编辑:尝试使用$watch。
编辑:将两组 html 移动到一个控制器后,DOM 操作使用 $watch()。感谢你们俩的帮助!
尝试将 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
}
}
});
};
相关文章:
- 可以't访问JavaScript函数范围中的变量
- 如何从chrome扩展访问angularjs根范围
- 访问内部功能范围的元素,而不是敲除中的外部
- 将 NodeJS 模块范围变量作为对象访问
- 主干.js(具有 Require.js)变量/范围访问问题
- AngularJS:从控制器访问特定的指令范围
- Angularjs:访问范围变量数组并计算平均值
- 如何访问嵌套的表单ng包含范围/字段
- 有棱角的如何获得ng重复项范围的访问权限
- 我怎么把范围弄错了?无法从jQuery访问此函数;.在“上”;
- webGL,javascript:尝试访问属性1中超出范围的顶点
- 是否有任何方法可以访问外部范围's变量
- 淘汰赛:can't从嵌套foreach访问父级范围的属性
- WebDriver Selenium:Javascript代码覆盖范围,无需服务器访问
- JS范围访问
- 从不同范围访问较新版本的变量(JavaScript / jQuery)
- 从外部绑定范围访问knockoutjs ViewModel
- 使用指令将具有范围访问权限的功能附加到html元素
- angular 1.5无范围访问http.get中的数据
- 从其他范围访问对象(javascript)