本文介绍了Angular - 指令中的更新范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在更新指令中的范围变量时遇到问题,我不想在指令中添加 HTML,是否可以只更新范围变量的值.获取事件链接将更新各种文本/链接/图像,但首先我只想更新范围变量名称
I'm having problems updating a scope var in a directive, I don't want to have to add HTML in the directive, is it possible to just have the value of the scope var updated. The get-event links will update a variety of text / links / images, but first I just want it to update the scope var name
Index.jade
div(ng-controller='AppCtrl')
h2 Hello {{name}}
a(href={{link}}) test
a.playlist(get-event rel='1000') 1000
br
br
a.playlist(get-event rel='2000') 2000
br
br
a.playlist(get-event rel='3000') 3000
指令.js
angular.module('myApp.directives', [])
.directive('getEvent', function($q, $http, $templateCache){
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
function loadData() {
var refId = attrs.rel;
console.log(refId);
$http.get('/api/event/'+refId, {
// cache: $templateCache
}).then(function(result) {
console.log(result);
scope.name = "NEW";
});
}
element.bind('click', function(event) {
scope.$apply(function() {
loadData();
});
});
}
}
});
controller.js
controller.js
angular.module('myApp.controllers', []).
controller('AppCtrl', function ($scope, $http) {
$http({
method: 'GET',
url: '/api/event/1000'
}).
success(function (data, status, headers, config) {
$scope.name = data.title;
}).
error(function (data, status, headers, config) {
$scope.name = 'Error!';
});
});
HTML 上的范围名称未更新,感谢您的帮助.
The scope name on the HTML doesn't update, thanks for any assistance.
推荐答案
我自己解决了,我最终改变了它,所以控制器中有一个函数可以进行更新.
I managed to solve myself, I ended up changing it so there is a function in controller that does the update.
在控制器中
$scope.update = function(id) {
//this is just a service factory to do the http request
updateEvent.getDetails(id).success(function (result) {
$scope.name =result.title;
});
};
在指令中
element.bind('click', function(event) {
scope.$apply(function() {
scope.update(refId);
});
});
谢谢你的帮助
这篇关于Angular - 指令中的更新范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!