chovy
chovy

Reputation: 75764

populate a form with a bookmarklet doesn't work in angularjs

I have a bookmarklet that just does some simple form input population but the angular form is still in an invalid state. Like nothing was ever changed.

I tried calling el.onchange() but that doesn't seem to do anything.

javascript:populate();

function populate(){
    var name = document.querySelector('input[name=name]');

    name.value = 'Fred';

    name.click();
    name.onchange();
}

Upvotes: 1

Views: 471

Answers (2)

mlo55
mlo55

Reputation: 6915

I used something similar to the code below to create my bookmarklet. Couple of things to consider.

  • Write your function (see example below)
  • Before creating your bookmarklet, test your function in the chrome console
  • Function tested, now remove the endlines (e.g. "replace all" in intellij (with regex enabled), replace "\n" with ""
  • create a new bookmark in the browser
  • edit the url, the url should begin with "javascript:", paste your one line url after that... you'll end up with something like "javascript:(function(){..." etc...

//nb: This function is not written to work in this page

(function () {
	//get the scope object for your controller
	var sc=angular.element("[ng-controller=myController]").scope();
	
	//grab your model
	var m=sc.mymodel;
	
	//some 'dodgy' date strings :)
	var today=new Date();
	var todayAsString=today.toLocaleDateString("en-GB");
	today.setDate(today.getDate()-183);
	var sixMonthsAgoStr=today.toLocaleDateString("en-GB");
	today.setDate(today.getDate()+365);
	var sixMonthsLaterStr=today.toLocaleDateString("en-GB");
	
	//pick a random oz state
	var states=["WA", "VIC","SA", "NT","NSW", "ACT", "QLD"];
	var ozState=states[Math.floor(Math.random()*(6)+1)];
	
	//update the model with some semi random values 
	m.actionDate=todayAsString;
	m.ausstralianState=ozState;
	m.streetNum=Math.floor((Math.random() * 1000) + 1);
	m.ID="CR" + Math.floor((Math.random() * 10000) + 1);
	m.manufactureYear="" + Math.floor(Math.random()*(2016-1960+1)+1960); //approx... between 1960 and 2016... 
	m.endDate=sixMonthsLaterStr;
	m.startDate=sixMonthsAgoStr;
	
	//MUST call $scope.apply() at the end.
	sc.$apply();
})();

Upvotes: 0

chovy
chovy

Reputation: 75764

Since I already have jQuery loaded, I was able to fix the issue by triggering the input event.

$('input[ng-model]').trigger('input');

Upvotes: 1

Related Questions