问题
I have a legacy page that has a <input type="hidden" id="myId" value="somenumber">
that is populated with Jquery (legacy code) asynchronously after the page loads for the first time. On this page I am trying to have an angularjs directive. The only problem is I am trying to watch on #myId value so I can use it for my directive but the value changes and triggers the watcher once and it is empty - it doesn't happen again when it actually gets a numercal value from jquery. What am I doing wrong? I tried with ng-value,ng-model but still I get undefined for those attempts. Also it is not possible to introduce routing etc to get the id from there.. Thanks
Here is my directive:
angular.module("myModule")
.directive("myDir", function () {
return {
restrict: 'A',
templateUrl: "template.html",
scope : {},
link: function (scope, element, attrs, ctrl) {
scope.$watch(function () { return $("#myId").val() }, function (newVal) { ctrl.myId= newVal});
},
controllerAs: 'myCtrl'
};
});
回答1:
Angular is unaware of the jquery change (obviously). You can emit the data in a custom event in jQuery, capture that event in angular and rebroadcast it to your directive to get it the first time.
Here is a plunkr with it working: http://plnkr.co/edit/RTIzEudC7TktDTSdqWnQ It will update the binding on the page after jquery emits an event 5 seconds after page load
//emit in jquery
$(document).trigger('customEvent', data);
app.run(['$rootScope', function ($rootScope) {
//capture jQuery events and re-broadcast them as angular events
//events to capture
var events = [
'customEvent'
];
//To Use: $scope.$on('eventName', function(ngEvent, jqEvent, data)
$(document).on(events.join(' '), function(e) {
$rootScope.$broadcast.apply($rootScope, [e.type].concat(Array.prototype.slice.call(arguments, 0)));
});
});
//listen for it in directive
scope.$on('customEvent', function(){
scope.$apply(function(){
//do stuff here and angular will be aware of it
});
});
来源:https://stackoverflow.com/questions/30513457/angularjs-legacy-integration-and-content-that-contains-asynchronously-changing-i